go:反射传参[]interface{}获取实际类型

根据传参进行解析并进行动态赋值,不需要知道原sturct是什么类型
比如实现的一个数据库字段动态解析就可以用到

import (
	"fmt"
	"reflect"
)
func ref(res interface{}){
	getType := reflect.TypeOf(res)
	getValue := reflect.ValueOf(res)

	// getElem := res.Type().Elem()
	v := reflect.New(getType.Elem()) 
	fmt.Println(getType,getType.Name(),getType.Kind())
	fmt.Println(v)
	fmt.Println("getValue",getValue)

	switch getType.Kind() {
	case  reflect.Slice:
		fmt.Println("Kind是:", getType.Kind())

		sturct_type := getType.Elem()
		fmt.Println("获取到slice内sturct类型:",sturct_type)
		fmt.Println("判断是什么类型的指针:",getType.Elem().Kind())
		var v reflect.Value
		if getType.Elem().Kind() == reflect.Ptr {
			subgetType := getType.Elem()
			sturct_type = subgetType.Elem()
			v = reflect.New(sturct_type)
			fmt.Println("生在对象信息1:",v,v.Elem(),sturct_type)
		}else{
			//根据类型生成&{},通过.Elem()再转为{}
			v = reflect.New(sturct_type).Elem()
			fmt.Println("生在对象信息2:",v,sturct_type.NumField())
		}
		//根据类型生成slice
		sl := reflect.MakeSlice(getType,0,0)
		sl = reflect.Append(sl,v)
		fmt.Println("反射获取slice :" , sl.Interface())
		// reflect.NewAt(ptr,sturct_type)
		//根据获取到的v可以进行动态赋值
		// reflect.NewAt(ptr,sturct_type)
	default:
		fmt.Println("err  ",getType)
	}

}

Golang Reflect反射的使用详解
golang interface to struct and string to struct
golang如何获取变量的类型:反射,类型断言
Go语言reflect.Elem()通过反射获取指针指向的元素类型

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值