[go language] 5.1.1 Basic concept of reflection

Reflection is a powerful and advanced concept in Go language, which allows us to introspect variables at runtime, including variable types, values, methods, etc.

First, to use reflection, we need to import  reflect the package:

import "reflect"

Reflected type (Type) and value (Value)

In Go, every variable has a type and a value. For example, for  var x int = 3, x the type is  intand the value is  3.

We can use  reflect.TypeOf and  reflect.ValueOf to get the type and value of a variable:

var x int = 3
fmt.Println(reflect.TypeOf(x))  // 输出 "int"
fmt.Println(reflect.ValueOf(x)) // 输出 "3"

These two functions return  reflect.Type and  reflect.Value type objects, which contain the type and value information of the original variable.

Manipulate reflection value

reflect.Value Provides a series of methods to manipulate reflected values. For example, we can  Int() get the integer value of the reflected value with the method:

var x int = 3
v := reflect.ValueOf(x)
fmt.Println(v.Int()) // 输出 "3"

Note that Int() the method will panic if the type of the value is not an integer. If you are not sure about the type of the value, you should first  Kind() check the type of the value with the method:

v := reflect.ValueOf(x)
if v.Kind() == reflect.Int {
    
    
    fmt.Println(v.Int()) // 输出 "3"
}

modify the value via reflection

You can also modify the value through reflection, but it should be noted that reflect.ValueOf an unmodifiable reflection value is returned. If you want to modify the original variable, you need to use  reflect.ValueOf(&x).Elem() reflection to get the address of the variable, and then  SetInt modify it with the method:

var x int = 3
v := reflect.ValueOf(&x).Elem()
v.SetInt(4)
fmt.Println(x) // 输出 "4"

The method here  Elem() returns the reflection value of the variable pointed to by the pointer, which is modifiable.

Summarize

Reflection is a very powerful feature of the Go language that allows us to introspect and modify variables at runtime. However, the use of reflection also needs to be cautious, because the type safety of reflection operations is checked at runtime, not at compile time. This means that if you make a mistake in writing your reflection code, you may panic at runtime.

The above is the basic concept of reflection, I hope it will be helpful to you. If you have any questions, please feel free to ask.

Guess you like

Origin blog.csdn.net/u010671061/article/details/132268622