Herks
Herks

Reputation: 897

Reflection type and value in Go

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?

Upvotes: 8

Views: 3219

Answers (1)

Stephen Weinberg
Stephen Weinberg

Reputation: 53398

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

Upvotes: 10

Related Questions