7

我不太清楚这个代码片段的行为。

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() 
    }
}

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

4

1 回答 1

8

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.

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()).

于 2012-10-29T05:15:13.477 回答