golang 反映值类型的切片

Ger*_*ens 6 go

fmt.Println(v.Kind())
fmt.Println(reflect.TypeOf(v))
Run Code Online (Sandbox Code Playgroud)

如何找出切片的反射值的类型?

以上结果在

v.Kind = slice
typeof = reflect.Value
Run Code Online (Sandbox Code Playgroud)

当我尝试Set创建错误的切片时它会崩溃

t := reflect.TypeOf([]int{})
s := reflect.MakeSlice(t, 0, 0)
v.Set(s)
Run Code Online (Sandbox Code Playgroud)

例如[]int{}[]string{}在创建之前,我需要知道反射值的确切切片类型,而不是这样。

Sno*_*lem 10

首先,我们需要通过测试来确保我们正在处理一个切片: 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.
}
Run Code Online (Sandbox Code Playgroud)