GO语言反射

反射可以作为了解,不必深入!

反射介绍

Go语音提供了一种机制在运行时更新变量和检查它们的值、调用它们的方法和它们支持的内在操作,但是在编译时并不知道这些变量的具体类型。这种机制被称为反射。反射也可以让我们将类型本身作为第一类的值类型处理。
Go程序在运行期使用reflect包访问程序的反射信息。

reflect包

反射是由 reflect 包提供支持. 它定义了两个重要的类型, Type 和 Value.任意接口值在反射中都可以理解为由reflect.Type和reflect.Value两部分组成,并且reflect包提供了reflect.TypeOf和reflect.ValueOf两个函数来获取任意对象的Value和Type。

TypeOf

reflect.TypeOf()函数可以获得任意值的类型对象(reflect.Type)。

func reflectTYpe(x interface{})  {
    v := reflect.TypeOf(x)
    fmt.Printf("type:%v\n",v)
}

func main() {
    var a int = 10
    reflectTYpe(a)  //type:int
    var b float32 = 1.1
    reflectTYpe(b)  //type:float32
    var c bool = false
    reflectTYpe(c)  //type:bool
}

type name和type kind

在反射中关于类型还划分为两种:类型(Type)和种类(Kind)。种类(Kind)就是指底层的类型.

type myInt int64

func reflectType(x interface{})  {
    t := reflect.TypeOf(x)
    fmt.Printf("type:%v kind:%v\n",t.Name(),t.Kind())
}

func main()  {
    var a int64
    var b *float32
    var c myInt
    var d rune
    reflectType(a)  //type:int64 kind:int64
    reflectType(b)  //type: kind:ptr
    reflectType(c)  //type:myInt kind:int64
    reflectType(d)  //type:int32 kind:int32

    type stu struct {
        name string
        id int64
        age int64
    }
    type person struct {
        do string
    }
    var e = stu{
        name:"ares",
        id:1,
        age:18,
    }
    var f = person{
        do:"study go",
    }
    reflectType(e)  //type:stu kind:struct
    reflectType(f)  //type:person kind:struct

Go语言的反射中像数组、切片、Map、指针等类型的变量,它们的.Name()都是返回空。
在reflect包中定义的Kind类型如下:

type Kind uint
const (
    Invalid Kind = iota  // 非法类型
    Bool                 // 布尔型
    Int                  // 有符号整型
    Int8                 // 有符号8位整型
    Int16                // 有符号16位整型
    Int32                // 有符号32位整型
    Int64                // 有符号64位整型
    Uint                 // 无符号整型
    Uint8                // 无符号8位整型
    Uint16               // 无符号16位整型
    Uint32               // 无符号32位整型
    Uint64               // 无符号64位整型
    Uintptr              // 指针
    Float32              // 单精度浮点数
    Float64              // 双精度浮点数
    Complex64            // 64位复数类型
    Complex128           // 128位复数类型
    Array                // 数组
    Chan                 // 通道
    Func                 // 函数
    Interface            // 接口
    Map                  // 映射
    Ptr                  // 指针
    Slice                // 切片
    String               // 字符串
    Struct               // 结构体
    UnsafePointer        // 底层指针
)
posted @ 2019-05-28 00:13  我是一条最咸的咸鱼  阅读(281)  评论(0编辑  收藏  举报
返回顶部