"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > What is the key distinction between reflect.Type and reflect.Value in Go reflection?

What is the key distinction between reflect.Type and reflect.Value in Go reflection?

Published on 2024-11-08
Browse:973

What is the key distinction between reflect.Type and reflect.Value in Go reflection?

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

  • Provides information about the type, such as its name, package, and underlying type.
  • Allows queries about its methods, fields, and other type-related data.
  • Does not contain the actual value of the variable passed to it.

reflect.Value

  • Represents the actual value of the variable passed to it.
  • Allows reading and setting values, manipulating the underlying data, and querying its methods and fields.
  • Contains a Type() method that returns its reflect.Type.

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() 
    }
}
  • t is a reflect.Type object representing the type of the variable pointed to by i.
  • v is a reflect.Value object representing the actual value of the variable pointed to by i.
  • tag is the tag of the first field (name) of the Person struct obtained through the reflect.Type.
  • name is the string representation of the first field obtained through the reflect.Value.

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.

Latest tutorial More>

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