我有一个 interface{}
变量,我知道它是一个指向 slice 的指针:
func isPointerToSlice(val interface{}) bool {
value := reflect.ValueOf(val)
return value.Kind() == reflect.Ptr && value.Elem().Kind() == reflect.Slice
}
但我发现很难将其类型转换为 []interface{}
变量:
if isPointerToSlice(val) {
slice, worked := reflect.ValueOf(val).Elem().Interface().([]interface{})
// 'worked' is false :(
}
这行不通。知道如何解决这个问题吗?
最佳答案
如果您只想将一个 slice 转换为 []interface{}
,您可以使用类似这样的东西:
func sliceToIfaceSlice(val interface{}) []interface{} {
rf := reflect.Indirect(reflect.ValueOf(val)) // skip the pointer
if k := rf.Kind(); k != reflect.Slice && k != reflect.Array {
// panic("expected a slice or array")
return nil
}
out := make([]interface{}, rf.Len())
for i := range out {
out[i] = rf.Index(i).Interface()
}
return out
}
关于go - interface{} 变量到 []interface{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35320357/