我正在编写一个程序,我需要访问作为 接口(interface){}
传递的指针的值。
package main
import (
"reflect"
)
type Test struct {
Names []string
}
func main() {
arr := []string{"a", "a", "a", "a", "a", "a"}
obj := new(Test)
obj.Names = arr
TestFunc(obj)
}
func TestFunc(obj interface{}){
rt := reflect.TypeOf(obj)
switch rt.Kind() {
case reflect.Struct:
return
case reflect.Ptr:
TestFunc(*obj) //<<--- There is the problem, cannot figure out how to access
//value of obj and *obj is not allowed here because of interface{} type.
}
}
这只是一个更大程序的示例,但足以解释我的问题。
所以问题是,当我将指针传递给 TestFunc()
时,我不知道如何在函数内部获取它的值。有可能吗?
我需要根据它是不是指针来做一些事情,所以如果我一直递归传递指针,程序就会失败。我需要从传递的指针中获取值(并传递前向值而不是指针)但我不确定是否可能因为我正在处理类型 interface{}
而不是指针和编译器不知道它是否要传递一个指针,所以它不允许像“*obj”这样的东西达到它的值。
最佳答案
如果你需要支持任意级别的指针那么你可以使用反射来获取值对象:
v:=reflect.ValueOf(obj)
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
v.Interface()
然而,在实践中实际需要这样做是很不寻常的。
对于您的功能,这可以像这样工作:
func TestFunc(obj interface{}){
rv := reflect.ValueOf(obj)
switch rv.Kind() {
case reflect.Struct:
// code here
return
case reflect.Ptr:
TestFunc(rv.Elm().Interface())
}
}
关于pointers - 如果它作为接口(interface)传递,则访问指针值{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45334244/