reflect——go反射三大定律

反射三大定律

反射第一定律:反射可以将“接口类型变量”转换为“反射类型对象”

1.使用v := reflect.TypeOf(a),对基本类型进行反射处理,因为TypeOf函数原型为:func TypeOf(I interface{})Type;故符合第一条定律

2.reflect.ValueOf().Type也可以返回一个reflect.Type类型的对象

3.reflect.ValueOf()获得到的对象,调用Kind函数会返回底层数据类型

package main

import (
    "fmt"
    "reflect"
)

type myInt int

func main() {
    var a myInt
    var b int
    v1 := reflect.ValueOf(a)
    v2 := reflect.ValueOf(b)
    fmt.Printf("v1 base type:%v
", v1.Kind())
    fmt.Printf("v2 base type:%v
", v2.Kind())
}

反射第二定律:反射可以将“反射类型对象”转换为“接口类型变量”

1.转换原型:func (v Value)interface() interface{},使用该函数可以将一个反射类型变量转换为我们想要的类型变量

func main() {

    str := "123"
    fmt.Printf("str type:%T
", str)
    v3 := reflect.ValueOf(str)
    fmt.Printf("v3 type:%v  v3 value:%v v3 kind:%v
", v3.Type(), v3, v3.Kind())
    tempstr := v3.Interface()
    fmt.Printf("tempstr value:%s  tempstr type:%T
", tempstr, tempstr)
}

反射第三定律:如果要修改“反射类型对象”其值必须是“可写的”

1.规定反射类型对象值是否可以修改在于该变量是否具有访问源变量地址的能力。即v := reflect.ValueOf(&p),传入地址,然后解引用,对变量进行赋值

2.判断对象值是否可以修改函数:v.CanSet()

func main() {

    var x float64 = 3.4

    p := reflect.ValueOf(&x) // Note: take the address of x.

    v := p.Elem()

    v.SetFloat(7.1)

    fmt.Println(“settability of v”,v.CanSet())

    fmt.Println(v.Interface())

    fmt.Println(x)

}
原文地址:https://www.cnblogs.com/single-dont/p/13550268.html