我有一个功能
func doStuff(inout *interface{}) {
...
}
此函数的目的是能够将任何类型的指针视为输入。 但是当我想用结构的指针调用它时,我遇到了错误。
type MyStruct struct {
f1 int
}
当调用 doStuff
ms := MyStruct{1}
doStuff(&ms)
我有
test.go:38: cannot use &ms (type *MyStruct) as type **interface {} in argument to doStuff
我怎样才能使 &ms
与 *interface{}
兼容?
最佳答案
没有“指向接口(interface)的指针”之类的东西(从技术上讲,您可以使用一个,但通常您不需要它)。
如“what is the meaning of interface{} in golang?”中所见,interface
是一个包含两个数据字的容器:
- 一个词用于指向值的基础类型的方法表,
- 另一个词用于指向该值所持有的实际数据。
所以去掉指针,doStuff
就可以正常工作了:接口(interface)数据将是&ms
,你的指针:
func doStuff(inout interface{}) {
...
}
见 this example :
ms := MyStruct{1}
doStuff(&ms)
fmt.Printf("Hello, playground: %v\n", ms)
输出:
Hello, playground: {1}
作为 newacct提到 in the comments :
Passing the pointer to the interface directly works because if
MyStruct
conforms to a protocol, then*MyStruct
also conforms to the protocol (since a type's method set is included in its pointer type's method set).In this case, the interface is the empty interface, so it accepts all types anyway, but still.
关于pointers - 在Golang中将结构指针转换为接口(interface)指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27178635/