在Golang中将结构指针转换为接口指针 [英] Cast a struct pointer to interface pointer in Golang
问题描述
我有一个函数
func doStuff(inout * interface {}){
...
}
此函数的目的是能够将任何类型的指针视为输入。
但是当我想使用一个结构体的指针调用它时,我有一个错误。
type MyStruct struct {
f1 int
}
当调用 doStuff
ms:= MyStruct {1}
doStuff(& ms)
我有
$ c> test.go:38:不能在doStuff的参数中使用& ms(类型* MyStruct)作为类型** interface {}
如何使& ms
与 * interface {}兼容
?
没有这样的东西作为指向接口的指针(技术上,你可以使用一个,不需要它。)
如:
ms:= MyStruct {1}
doStuff(& ms)
fmt.Printf(Hello,playground:%v \\\
,ms)
输出:
您好,playground:{1}
< a href =http://stackoverflow.com/users/86989/newacct> newacct mentions 在注释中:
将指针传递到接口直接工作,因为如果
MyStruct
符合协议,则* MyStruct
也符合协议(因为类型的方法set包含在其指针类型的方法集中)。
在这种情况下,接口是空接口,所以它接受所有类型,但仍然。
I have a function
func doStuff(inout *interface{}) {
...
}
the purpose of this function is to be able to treat a pointer of any type as input. But when I want to call it with a the pointer of a struct I have an error.
type MyStruct struct {
f1 int
}
When calling doStuff
ms := MyStruct{1}
doStuff(&ms)
I have
test.go:38: cannot use &ms (type *MyStruct) as type **interface {} in argument to doStuff
How can I cast &ms
to be compatible with *interface{}
?
There is no such thing as a "pointer to an interface" (technically, you can use one, but generally you don't need it).
As seen in "what is the meaning of interface{} in golang?", interface
is a container with two words of data:
- one word is used to point to a method table for the value’s underlying type,
- and the other word is used to point to the actual data being held by that value.
So remove the pointer, and doStuff
will work just fine: the interface data will be &ms
, your pointer:
func doStuff(inout interface{}) {
...
}
See this example:
ms := MyStruct{1}
doStuff(&ms)
fmt.Printf("Hello, playground: %v\n", ms)
Output:
Hello, playground: {1}
As newacct mentions 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.
这篇关于在Golang中将结构指针转换为接口指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!