Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection type and value in Go

Tags:

reflection

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?

like image 234
Herks Avatar asked Oct 29 '12 03:10

Herks


People also ask

What is reflect value in Go?

Reflection is provided by the reflect package. It defines two important types, Type and Value . A Type represents a Go type. It is an interface with many methods for discriminating among types and inspecting their components, like the fields of a struct or the parameters of a function.

Does Golang have reflection?

Reflection is the ability of a program to introspect and analyze its structure during run-time. In Go language, reflection is primarily carried out with types. The reflect package offers all the required APIs/Methods for this purpose.

How do you use reflection in Go?

You can use reflection to get the type of a variable var with the function call varType := reflect. TypeOf(var). This returns a variable of type reflect. Type, which has methods with all sorts of information about the type that defines the variable that was passed in.

What is reflect indirect?

The reflect. Indirect() Function in Golang is used to get the value that v points to, i.e., If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v. To access this function, one needs to imports the reflect package in the program.


1 Answers

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

like image 140
Stephen Weinberg Avatar answered Sep 20 '22 17:09

Stephen Weinberg