简体   繁体   English

将结构指针强制转换为Golang中的接口指针

[英]Cast a struct pointer to interface pointer in Golang

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 在调用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{} ? 如何使用&ms来兼容*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: 如“ golang中接口{}的含义是什么? ”中所示, interface是一个包含两个数据字的容器:

  • 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: 所以删除指针, doStuff将正常工作:接口数据将是&ms ,你的指针:

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 : 正如newacct 在评论中提到:

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). 将指针直接传递给接口是有效的,因为如果MyStruct符合协议,那么*MyStruct也符合协议(因为类型的方法集包含在其指针类型的方法集中)。

In this case, the interface is the empty interface, so it accepts all types anyway, but still. 在这种情况下,接口是空接口,因此它仍然接受所有类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM