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()通过反射获取指针指向的元素类型

你可能感兴趣的:(golang)