go语法:reflect

参考:

https://studygolang.com/articles/34347 (反射主要用法)
http://books.studygolang.com/gopl-zh/ch12/ch12-02.html(reflect.Type 和 reflect.Value)

http://books.studygolang.com/GoExpertProgramming/chapter06/6.1-reflect.html(反射3定律)

https://www.topgoer.com/%E5%B8%B8%E7%94%A8%E6%A0%87%E5%87%86%E5%BA%93/%E5%8F%8D%E5%B0%84.html(反射基本使用)

 

反射

1,Go语言提供了一种机制,能够在运行时更新变量和检查它们的值、调用它们的方法和它们支持的内在操作,而不需要在编译时就知道这些变量的具体类型。

2,reflect包的核心有两种类型,分别为reflect.Valuereflect.Type。前一种类型用于存储任何类型的值,而后一种类型用于表示任意类型。

3,反射的原理是基于golang的unsafe.Pointer内存操作和类型系统

4,反射代理了各种类型的属性和方法,所以有助于理解变量和类型在内存上的特点和使用上的特征,对理解深入理解语言大有裨益

Value:反射值

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

第一个成员是Type

第二个成员是 原变量的指针信息

第三个成员是Kind:golang的类型系统

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
    // function for comparing objects of this type
    // (ptr to object A, ptr to object B) -> ==?
    equal     func(unsafe.Pointer, unsafe.Pointer) bool
    gcdata    *byte   // garbage collection data
    str       nameOff // string form
    ptrToThis typeOff // type for pointer to this type, may be zero
}

 

posted @ 2021-08-23 10:58  小匡程序员  阅读(68)  评论(0编辑  收藏  举报