go反射

反射的功能很强大

通过reflect.typeof 方法,我们可以获取一个变量的类型信息reflect.type ,

通过reflect.type类型对象,我们可以访问到其对应类型的各项类型信息。我们可以创建一个hero结构体,通过reflect.typeof来查看其对应的类型信息。

package main

import (
    "fmt"
    "reflect"
)

type Person interface {
    //和人说hello
    SayHello(name string)
    //跑步
    Run()string
}

type Hero struct {
    Name string
    Age int
    Speed int
}

func(hero *Hero) SayHello(name string){
    fmt.Println("hello"+name,",I am "+hero.Name)
}

func(hero *Hero) Run()string{
    fmt.Println("I am running at speed"+string(hero.Speed))
    return "Running"
}

func main(){
    //获取实例的反射类型对象
    typeOfHero :=reflect.TypeOf(Hero{})
    fmt.Printf("Hero's type is %s,kind is %s",typeOfHero,typeOfHero.Kind())
    fmt.Println("2")
    //声明一个Person接口,并用Hero作为接收器
    var person Person = &Hero{}
    //获取接口person的类型对象
    typeOfPerson :=reflect.TypeOf(person)
    //打印person的方法类型和名称
    for i:=0;i<typeOfPerson.NumMethod();i++{
        fmt.Printf("method is %s,type is %s,kind is %s.
",
            typeOfPerson.Method(i).Name,
            typeOfPerson.Method(i).Type,
            typeOfPerson.Method(i).Type.Kind())

    }
    method,_:=typeOfPerson.MethodByName("Run")
    fmt.Printf("method is %s,type is %s,kind is %s.
",
        method.Name,method.Type,method.Type.Kind())
}

reflect.value反射值对象

使用type类型对象可以获取到变量的类型与种类,但无法获取到变量的值,更无法对值进行修改,所以需要使用reflect.valueof获取反射变量的实例信息value,通过value对变量的值进行查看修改,

name :="小明"
    valueOfName :=reflect.ValueOf(name)
    fmt.Println("三年二班",valueOfName.Interface())//通过value.interface获取变量的值

如果取值变量类型与取值方式不匹配,那么程序会报panic,

可以用reflect.new方法根据变量的type对象创建一个相同类型的新变量,值以value的形式返回,

typeOfHero :=reflect.TypeOf(Hero{})
    heroValue :=reflect.New(typeOfHero)
    fmt.Printf("hero's type is %s,kind is %s
",heroValue.Type(),heroValue.Kind())

对变量的修改可以通过value.set方法实现,

    name :="小明"
    valueOfName :=reflect.ValueOf(&name)
    valueOfName.Elem().Set(reflect.ValueOf("小红"))
    fmt.Printf(name)                                        //将小明变成小红

一个变量值是否可以寻址,可以通过#CanAddr方法来判断

valueOfName.CanAddress

原文地址:https://www.cnblogs.com/gagaAurora/p/13715612.html