Reflection Types and Values in Go
Reflections in Go allow developers to inspect and manipulate types and values at runtime. Understanding their distinctions is crucial for effective use of reflection.
Type vs. Value in Reflection
In reflection, reflect.TypeOf(i) returns a reflect.Type object, while reflect.ValueOf(i) returns a reflect.Value object.
reflect.Type
reflect.Value
Example
In the code snippet:
func show(i interface{}) {
switch t := i.(type) {
case *Person:
t := reflect.TypeOf(i) // Get the type of *Person
v := reflect.ValueOf(i) // Get the value of i
tag := t.Elem().Field(0).Tag
name := v.Elem().Field(0).String()
}
}
By understanding the difference between types and values in reflection, developers can leverage the power of reflection in various scenarios, including introspection, dynamic method invocation, and data serialization.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3