pointers - 如果它作为接口(interface)传递,则访问指针值{}

标签 pointers go interface

我正在编写一个程序,我需要访问作为 接口(interface){} 传递的指针的值。

playground

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/

相关文章:

Symfony 4.4 翻译界面问题

generics - 编写比 Java 更优雅的 Copyable 接口(interface)

c++ - 如何创建 const 指针的动态数组?

arrays - 在内存中将 []byte 转换为 [32]byte 而不复制数据

c - C语言指针中的*p++,*++p,++*p有什么区别?

go - 在不创建缓冲区的情况下写入标准输出

go - 模拟结构参数

Angular 6 类型错误 : Cannot read property 'e4b7...f' of undefined

c - 链接列表不兼容的指针类型

c++ - 数组结束时指针不应该指向 nullptr 吗?