将”reflect”转化为可比较的数据。

huangapple go评论107阅读模式
英文:

turn reflect into comparable data

问题

我想要使用reflect来比较对象的类型。以下是我的代码:

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. func main() {
  7. tst := "cat"
  8. if reflect.TypeOf(tst).Kind() == reflect.String {
  9. fmt.Println("It's a string!")
  10. }
  11. }

这样会给我一个错误提示type string is not an expression。我该如何只使用 reflect来修复这个问题?(不使用类型切换等其他方法)

英文:

I want to be able to compare the type of an object using reflect. Here is my code:

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. func main() {
  7. tst := "cat"
  8. if reflect.TypeOf(tst) == string {
  9. fmt.Println("It's a string!")
  10. }
  11. }

This gives me an error type string is not an expression. How can I fix this only using reflect? (no type switches, etc.)

答案1

得分: 2

两个简单的选项:

使用Kind

  1. if reflect.TypeOf(tst).Kind() == reflect.String {
  2. fmt.Println("It's a string!")
  3. }

使用TypeOf另一个字符串:

  1. if reflect.TypeOf(tst) == reflect.TypeOf("") {
  2. fmt.Println("It's a string!")
  3. }

然而,个人而言,我更喜欢使用类型切换或类型检查(即if _, ok := tst.(string); ok {...})。

英文:

Two simple options:

use Kind:

  1. if reflect.TypeOf(tst).Kind() == reflect.String {
  2. fmt.Println("It's a string!")
  3. }

use TypeOf another string:

  1. if reflect.TypeOf(tst) == reflect.TypeOf("") {
  2. fmt.Println("It's a string!")
  3. }

However, personally I'd prefer a type switch or type check (i.e. if _, ok := tst.(string); ok {...}

huangapple
  • 本文由 发表于 2016年2月21日 22:05:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/35537094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定