我有一个功能
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 {}兼容?
没有像“指向界面的指针”这样的东西(在技术上,你可以使用它,但通常你不需要它).
如“what is the meaning of interface{} in golang?”所示,界面是一个包含两个数据字的容器:
>一个单词用于指向值的底层类型的方法表,
>而另一个单词用于指向由该值保存的实际数据.
所以删除指针,并且doStuff将正常工作:接口数据将为& ms,您的指针:
func doStuff(inout interface{}) { ... }
ms := MyStruct{1} doStuff(&ms) fmt.Printf("Hello,playground: %v\n",ms)
输出:
Hello,playground: {1}
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.