Go中的反射类型和值

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

Reflection type and value in Go

问题

我对这段代码的行为不是很清楚。

func show(i interface{}) {
    switch t := i.(type) {
    case *Person:
      t := reflect.TypeOf(i)  // t 包含什么?
      v := reflect.ValueOf(i)  // v 包含什么?
      tag := t.Elem().Field(0).Tag
      name := v.Elem().Field(0).String() 
    }
}

反射中类型和值的区别是什么?

英文:

I'm not very clear about what this code snippet behaves.

func show(i interface{}) {
    switch t := i.(type) {
    case *Person:
      t := reflect.TypeOf(i)  //what t contains?   
      v := reflect.ValueOf(i)  //what v contains?
      tag := t.Elem().Field(0).Tag
      name := v.Elem().Field(0).String() 
    }
}

What is the difference between the type and value in reflection?

答案1

得分: 9

reflect.TypeOf() 返回一个 reflect.Type,而 reflect.ValueOf() 返回一个 reflect.Valuereflect.Type 允许您查询与相同类型的所有变量相关联的信息,而 reflect.Value 允许您查询信息并对任意类型的数据执行操作。

此外,reflect.ValueOf(i).Type() 等同于 reflect.TypeOf(i)

在上面的示例中,您使用 reflect.Type 来获取 Person 结构体中第一个字段的“标签”。您首先使用 *Person 的 Type。为了获取 Person 的类型信息,您使用了 t.Elem()。然后,您使用 .Field(0).Tag 获取了关于第一个字段的标签信息。实际传递的值 i 并不重要,因为第一个字段的标签是类型的一部分。

您使用 reflect.Value 来获取值 i 的第一个字段的字符串表示形式。首先,您使用 v.Elem() 获取指向 i 所指向的结构体的 Value,然后访问第一个字段的数据(.Field(0)),最后将该数据转换为字符串(.String())。

英文:

reflect.TypeOf() returns a reflect.Type and reflect.ValueOf() returns a reflect.Value. A reflect.Type allows you to query information that is tied to all variables with the same type while reflect.Value allows you to query information and preform operations on data of an arbitrary type.

Also reflect.ValueOf(i).Type() is equivalent to reflect.TypeOf(i).

In the example above, you are using the reflect.Type to get the "tag" of the first field in the Person struct. You start out with the Type for *Person. To get the type information of Person, you used t.Elem(). Then you pulled the tag information about the first field using .Field(0).Tag. The actual value you passed, i, does not matter because the Tag of the first field is part of the type.

You used reflect.Value to get a string representation of the first field of the value i. First you used v.Elem() to get a Value for the struct pointed to by i, then accessed the first Field's data (.Field(0)), and finally turned that data into a string (.String()).

huangapple
  • 本文由 发表于 2012年10月29日 11:59:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/13115677.html
匿名

发表评论

匿名网友

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

确定