Home > Backend Development > Golang > 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?

Susan Sarandon
Release: 2024-10-28 01:56:30
Original
301 people have browsed it

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:

<code class="go">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() 
    }
}</code>
Copy after login
  • 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.

The above is the detailed content of What is the key distinction between reflect.Type and reflect.Value in Go reflection?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template