Type of reflection and value in Go

I do not quite understand what this piece of code does.

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 type and value in reflection?

+4
source share
1 answer

reflect.TypeOf() returns reflect.Type and reflect.ValueOf() returns reflect.Value . A reflect.Type allows reflect.Type to request information that is bound to all variables of the same type, while reflect.Value allows reflect.Value to request information and pre-processing data of an arbitrary type.

In the above example, you use reflect.Type to get the "tag" of the first field in the Person structure. You start with a type for *Person . To get information about the type 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, since 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 i value. First you used v.Elem() to get the value for the structure pointed to by i , then .Field(0) first data of the field ( .Field(0) ) and finally turned that data into a string ( .String() ).

+6
source

Source: https://habr.com/ru/post/1442670/


All Articles