我有一个interface{}变量,我知道它是一个指向切片的指针:
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 :(
}这不管用。你知道我该怎么解决这个问题吗?
发布于 2016-02-11 00:21:04
您可以简单地使用type assertion来获取存储在接口中的值,例如
if isPointerToSlice(val) {
var result []interface{}
result = *val.(*[]interface{})
fmt.Println(result)
} else {
fmt.Println("Not *[]interface{}")
}如您所说,存储在接口中的值的类型是指向[]interface{}的指针,即*[]interface{}。类型断言的结果将是一个指针,只需取消对其的引用即可获得切片[]interface{}。
result := *val.(*[]interface{}) // type of result is []interface{}在Go Playground上试试。
同样,你的尝试也是有效的:
slice, worked := reflect.ValueOf(val).Elem().Interface().([]interface{})
fmt.Println(slice, worked)这是证明您的解决方案有效的edited the Playground example。
但是使用反射是不必要的(因为它可以通过类型断言来完成)。
还要注意,*[]interface{}和*[]someOtherType是两种不同的类型,如果val中有其他类型,则无法获得*[]interface{}的值。
发布于 2016-02-11 01:29:21
Icza的答案很好,特别是当你不能确定你得到的是一个接口切片时,尤其有效。但是,如果你根本不想为反射包而烦恼,并且想要保持导入的代码很少,你可以使用类型切换,只使用内置的方法来获得相同的功能。
使用此方法,您可以将代码缩短为:
package main
import (
"fmt"
)
func main() {
s := []interface{}{"one", 2}
p := &s
do(p)
}
func do(val interface{}) {
switch val.(type){
case *[]interface{}:
var result []interface{}
result = *val.(*[]interface{})
fmt.Println(result)
}
}游乐场:http://play.golang.org/p/DT_hb8JcVt
缺点是,如果您事先不知道正在接收的片的确切类型,那么除非列出所有可能的处理和断言类型,否则这将不会起作用。
https://stackoverflow.com/questions/35320357
复制相似问题