TypeOf / ValueOf
t := reflect.TypeOf(42) // int
v := reflect.ValueOf("hi") // string value
fmt.Println(t.Kind(), v.Kind()) // int string
reflectInspect and manipulate arbitrary values at runtime. Slow and complex — prefer interfaces and generics when you can.
t := reflect.TypeOf(42) // int
v := reflect.ValueOf("hi") // string value
fmt.Println(t.Kind(), v.Kind()) // int string
type MyInt int
reflect.TypeOf(MyInt(1)).Kind() // reflect.Int
reflect.TypeOf(MyInt(1)).Name() // "MyInt"
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
t := reflect.TypeOf(User{})
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
fmt.Println(f.Name, f.Type, f.Tag.Get("json"))
}
x := 1
v := reflect.ValueOf(&x).Elem() // Elem dereferences
v.SetInt(42)
// x == 42
m := reflect.ValueOf(obj).MethodByName("Greet")
out := m.Call([]reflect.Value{reflect.ValueOf("world")})
fmt.Println(out[0].String())
reflect.DeepEqual([]int{1,2}, []int{1,2}) // true
reflect.DeepEqual(map[string]int{"a":1}, map[string]int{"a":1}) // true