加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang 反射应用(二)

发布时间:2020-12-16 09:29:48 所属栏目:大数据 来源:网络整理
导读: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 } //定义

golang反射应用(二)

package test

import (
    "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.)反射的应用有适配器定义,结构体创建和对结构体字段进行操作

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读