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?
reflect.TypeOf()returns a reflect.Type andreflect.ValueOf()returns a reflect.Value. Areflect.Typeallows you to query information that is tied to all variables with the same type whilereflect.Valueallows you to query information and preform operations on data of an arbitrary type.Also
reflect.ValueOf(i).Type()is equivalent toreflect.TypeOf(i).In the example above, you are using the
reflect.Typeto get the "tag" of the first field in the Person struct. You start out with the Type for*Person. To get the type information ofPerson, you usedt.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.Valueto get a string representation of the first field of the valuei. First you usedv.Elem()to get a Value for the struct pointed to byi, then accessed the first Field’s data (.Field(0)), and finally turned that data into a string (.String()).