反射的应用-Interface和reflect.Value转换
反射的应用#
Interface 和 reflect.Value 转换#
在反射中,变量、interface {}、reflect.Value 是可以相互转换的。实际开发中,这种应用的场景也是最多的。通常的使用方式为:
有一个 interface {} 作为参数的函数,专门用于做反射。如 reflectTest
var stu Student
var n int
func reflectTest(i interface{}) {
ReVal := reflect.ValueOf(i)
iValue := ReVal.Interface()
v := iVal.(Student)
}
这个函数既可以指向 普通的 int 类型变量,也可以指向复杂的自定义 struct 结构体类型变量。因此,可以在 reflectTest 内部使用 reflect.ValueOf () 函数将 interface {} 转成 reflect.Value 类型。
interface{} ——> reflect.Value
使用的方法为:
ReVal := reflect.ValueOf(i)
本方法返回 v 当前持有的值
iVal := ReVal.interface()
针对返回的这个 interface 我们可以使用类型断言,切实的指向一个具体的数据类型。
interface {} ——> 原有的变量类型
v := iVal.(Student) // 可将v转为 结构体 Student类型
v := iVal.(int) // 可将v转为 基础 int 类型
总的来说,在反射中,变量、interface {}、reflect.Value 类型之间可以遵循这样的转换关系。
变量 ——> 传参 interface ——> valueOf () ——> reflect.Value ——> 调用 Interface () 函数 ——> interface () ——> 断言 ——> 变量
如图所示:
推荐文章: