我想填充切片数据,但是使用reflect.kind()只让我知道字段(0)是片,但我不知道它是哪种类型的片,它是int[]还是string[]还是其他类型的片
我知道什么切片数据类型,仓促设定值会恐慌,有些知道如何获取切片类型的信息吗?
func WhatSlice(isAny any) {
vof := reflect.ValueOf(isAny)
if vof.Kind() != reflect.Struct {
return
}
switch vof.Field(0).Kind() {
case reflect.Slice:
for i := 0; i < vof.Field(0).Len(); i++ {
// how to know this field is []int or []string?
// vof.Field(0).Index(i).Set()
}
default:
return
}
}发布于 2022-08-17 10:09:53
使用Type,您可以直接获得切片类型,但是应该使用字符串类型来区分它。
func WhatSlice(isAny any) {
vof := reflect.ValueOf(isAny)
if vof.Kind() != reflect.Struct {
return
}
switch vof.Field(0).Kind() {
case reflect.Slice:
switch vof.Field(0).Type().String() {
case "[]int":
fmt.Println("int here")
case "[]string":
fmt.Println("string here")
}
default:
return
}
}发布于 2022-08-17 08:14:20
您可以在使用vof.Field(0).Index(0).Kind()调用循环之前检查它。
func WhatSlice(isAny any) {
vof := reflect.ValueOf(isAny)
if vof.Kind() != reflect.Struct {
return
}
switch vof.Field(0).Kind() {
case reflect.Slice:
if vof.Field(0).Len() == 0 {
fmt.Println("empty slice")
return
}
switch vof.Field(0).Index(0).Kind() {
case reflect.Int:
fmt.Println("int here")
// for i := 0; i < vof.Field(0).Len(); i++ {
// how to know this field is []int or []string?
// vof.Field(0).Index(i).Set()
// }
case reflect.String:
fmt.Println("string here")
}
default:
return
}
}发布于 2022-08-17 08:15:39
https://stackoverflow.com/questions/73384785
复制相似问题