fmt.Println(v.Kind())
fmt.Println(reflect.TypeOf(v))
如何找出切片的反射值的类型?
上面的结果是
v.Kind = slice
typeof = reflect.Value
当我尝试Set
如果我创建了错误的切片,它会崩溃
t := reflect.TypeOf([]int{})
s := reflect.MakeSlice(t, 0, 0)
v.Set(s)
例如[]int{}
代替[]string{}
因此,在创建反射值之前,我需要知道反射值的确切切片类型。
首先,我们需要通过测试确保我们正在处理一个切片:reflect.TypeOf(<var>).Kind() == reflect.Slice
如果没有这项检查,您将面临运行时恐慌的风险。因此,既然我们知道我们正在使用切片,那么查找元素类型就很简单:typ := reflect.TypeOf(<var>).Elem()
由于我们可能期望许多不同的元素类型,因此我们可以使用 switch 语句来区分:
t := reflect.TypeOf(<var>)
if t.Kind() != reflect.Slice {
// handle non-slice vars
}
switch t.Elem().Kind() { // type of the slice element
case reflect.Int:
// Handle int case
case reflect.String:
// Handle string case
...
default:
// custom types or structs must be explicitly typed
// using calls to reflect.TypeOf on the defined type.
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)