golang 反射应用(二)

golang 反射应用(二),第1张

概述golang反射应用(二) package testimport ( "reflect" "testing")//定义适配器func TestReflect(t *testing.T){ //声明回调函数 call1 := func(v1,v2 int){ t.Log(v1,v2) //1 2 } call2 := golang反射应用(二)
package testimport (    "reflect"    "testing")//定义适配器func TestReflect(t *testing.T){    //声明回调函数    call1 := func(v1,v2 int){        t.Log(v1,v2)   //1 2    }    call2 := func(v1,v2 int,s string){        t.Log(v1,v2,s)   //1 2 test2    }    //定义全局变量    var (        function reflect.Value        inValue []reflect.Value        n int    )    brIDge := func(call interface{},args... interface{}){        n = len(args)        inValue = make([]reflect.Value,n)        for i:=0;i<n;i++{            inValue[i] = reflect.ValueOf(args[i])        }        //将一个interface转换我Value类型        function = reflect.ValueOf(call)        //传入参数,直接去调用函数        function.Call(inValue)    }    //桥接函数,调用不同的函数    brIDge(call1,1,2)    brIDge(call2,2,"test2")}type user struct {    UserID string    name string}//实例化一个对象,并为该实例赋值func TestRelectStructPtr(t *testing.T){    var (        model *user        st reflect.Type        elem reflect.Value    )    st = reflect.TypeOf(model)   //获取类型 *user    t.Log("reflect.TypeOf",st.Kind().String())   //ptr    st = st.Elem()   //st指向的类型    t.Log("reflect.TypeOf.Elem",st.Kind().String())  //struct    elem = reflect.New(st)   //New返回一个Value类型值,该值持有一个指向类型为type的新申请的零值指针    t.Log("reflect.New",elem.Kind().String())  //ptr    t.Log("reflect.New.Elem",elem.Elem().Kind().String())   //reflect.New.Elem struct    //model就是创建的user结构体变量(实例)    model = elem.Interface().(*user)  //model是*user 它的指向和elem是一样的    elem =elem.Elem()  //取得elem指向的值    elem.FIEldByname("UserID").SetString("123456")  //赋值    elem.FIEldByname("name").SetString("jack")    t.Log("model model.name",model,model.name)    //model model.name &{123456 jack} jack}

总结: (1.)反射的应用有适配器定义,结构体创建和对结构体字段进行 *** 作

总结

以上是内存溢出为你收集整理的golang 反射应用(二)全部内容,希望文章能够帮你解决golang 反射应用(二)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1268388.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存