TypeOf and ValueOf
To use reflection, you will need to get familiar with two types defined in the reflect
package:
reflect.Type reflect.Value
Both of these types provide utility functions that give you access to the dynamic runtime information of the object.
These two functions give you a handle on the Type
and Value
of the object:
func TypeOf( interface{}) Type func ValueOf( interface{}) Value
The following program uses the two functions to print the Type
and Value
of the object being passed:
func main() { var x = 5 Print(x) var y = []string{"test"} Print(y) var z = map[string]string{"a": "b"} Print(z) } func Print(a interface{}) { fmt.Println("Type: ", reflect.TypeOf(a)) fmt.Println("Value: ", reflect.ValueOf(a)) }
The output of the preceding program should print the Type
of x
:
$ go run main.go Type: int Value 5...