Go language core programming (6)-reflection

Go language core programming (6)-reflection

Note: This article is a personal reading note of "Go Language Core Programming" (Li Wenta/Work)

reflect.Type

type rtype struct {
    size uintptr
    ptrdata uintptr//number of bytes in the type that can contain pointers
    hash uint32//hash of type; avoids computation in hash tables
    tflag tflag//extra type information flags
    align uint8//alignment of variable with this type
    fieldAlign uint8//alignment of struct field with this type
    kind uint8//enumeration for C
    alg *typeAlg//algorithm table
    gcdata *byte//garbage collection data
    str nameOff//string form
    ptrToThis typeOff//type for pointer to this type, may be zero
}
26 basic types
const (
    Invalid Kind = iota
    Bool
    Int
    Int8
    Int16
    Int32
    Int64
    Uint
    Uint8
    Uint16
    Uint32
    Uint64
    Uintptr
    Float32
    Float64
    Complex64
    Complex128
    Array
    Chan
    Func
    Interface
    Map
    Ptr
    Slice
    String
    Struct
    UnsafePointer
)

reflect. Value

reflect. Value represents the value information of the instance, reflect.Value is a struct, and provides a series of methods to users. One is the type pointer typ of the value, the other is the pointer ptr to the value, and the last is the flag field.

type Value struct {
    typ *rtype
        ptr unsafe.Pointer
    flag
}

Common API

From the instance to the Value Obtain the Value object through the instance, directly use the reflect.ValueOf() function

func ValueOf(i interface {})

From the instance to the TypeValue to obtain the Type of the reflection object through the instance, directly use the reflect.Typeof() function

func TypeOf(i interface{}) type

There is only type information from Type to Value Type, so the value of an instance cannot be obtained directly from a Type interface variable, but the Value of a new instance can be constructed from the Type. The reflect package provides two methods.

func New(typ Type)Value
func Zero(typ Type) Value

If you know the underlying storage address of a type value, there is another function that can restore Value based on the type and the address value

func NewAt(typ Type,p unsafe. Pointer) Value

From Value to Type, you can directly call the method of Value from the reflection object Value to Type, because Value stores the pointer to the Type type internally.

func(v Value)Type()Type

3.laws of reflection

1 Reflection can get the reflection object from the interface value. 2 Reflection can obtain the interface value from the reflection object. 3 If you want to modify a reflection object, its value must be modifiable.

Reference: https://cloud.tencent.com/developer/article/1438475 Go language core programming (6)-reflection-cloud + community-Tencent Cloud