英文:
golang reflect value kind of slice
问题
你可以使用reflect.TypeOf函数来获取切片的反射值的类型。以下是示例代码:
t := reflect.TypeOf(v.Interface())
fmt.Println(t)
这将打印出切片的类型。在你的例子中,它将打印出[]int或[]string。
希望这可以帮助到你!
英文:
fmt.Println(v.Kind())
fmt.Println(reflect.TypeOf(v))
How can I find out the type of the reflect value of a slice?
The above results in
v.Kind = slice
typeof = reflect.Value
When i try to Set it will crash if i create the wrong slice
t := reflect.TypeOf([]int{})
s := reflect.MakeSlice(t, 0, 0)
v.Set(s)
For example []int{} instead of []string{} so I need to know the exact slice type of the reflect value before I create one.
答案1
得分: 14
首先,我们需要确保我们正在处理一个切片,可以通过测试以下代码来实现:reflect.TypeOf(<var>).Kind() == reflect.Slice
如果没有进行这个检查,可能会导致运行时错误。所以,现在我们知道我们正在处理一个切片后,找到元素类型就很简单了:typ := reflect.TypeOf(<var>).Elem()
由于我们可能期望有多种不同的元素类型,我们可以使用switch语句来区分:
t := reflect.TypeOf(<var>)
if t.Kind() != reflect.Slice {
    // 处理非切片变量
}
switch t.Elem().Kind() {  // 切片元素的类型
    case reflect.Int:
        // 处理int类型的情况
    case reflect.String:
        // 处理string类型的情况
    ...
    default:
        // 自定义类型或结构体必须显式指定类型,
        // 使用定义类型的reflect.TypeOf调用。
}
英文:
To start, we need to ensure that the we're dealing with a slice by testing: reflect.TypeOf(<var>).Kind() == reflect.Slice
Without that check, you risk a runtime panic.  So, now that we know we're working with a slice, finding the element type is as simple as: typ := reflect.TypeOf(<var>).Elem()
Since we're likely expecting many different element types, we can use a switch statement to differentiate:
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.
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论