当我动态创建一个指向类型的指针,然后将其传递给解码函数时,理论上它似乎是正确编写的:
x := reflect.New(structType)
decode(x)
但是,当您打印 x
时,它看起来像是该类型的零值。该类型绝对正确且符合预期。
另一方面,当我创建类型并直接向它传递指针时,它工作得很好:
directoryEntry := DirectoryEntry{}
decode(&directoryEntry)
内容由decode()
正确设置,并且在打印时是正确的。
所以,看来我必须将类型的值传递给 decode()
而不是引用?
有人可以指出我必须缺少什么吗?一些 Google 查询没有帮助,看来我一定遗漏了一些小东西。
最佳答案
reflect.New()
返回一个指向传递类型值的指针,但返回的指针被包装在 reflect.Value
中。结构!
使用Value.Interface()
“解开”它,并将指针作为 interface{}
传递给 decode()
:
x := reflect.New(structType)
p := x.Interface()
decode(p)
当您打印 reflect.Value
时,您通常不会看到差异,因为 reflect.Value
类型被视为特殊的;引用自Value.String()
:
The fmt package treats Values specially. It does not call their String method implicitly but instead prints the concrete values they hold.
关于pointers - 通过反射创建类型并通过引用传递可以编译但不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57779248/