pointers - 在Golang中将结构指针转换为接口(interface)指针

标签 pointers struct interface casting go

我有一个功能

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是一个包含两个数据字的容器:

  • 一个词用于指向值的基础类型的方法表,
  • 另一个词用于指向该值所持有的实际数据。

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/

相关文章:

JAVA 错误的变量引用?收到奇怪的输出 - 可能是内存地址?

C将二维数组指向另一个二维数组

C++ vector 丢失指针引用

c - 在这些声明下,以下表达式是什么类型,它们是否正确?

C++ 如何将值从一种结构传递到另一种结构?

java - 不是静态java接口(interface)

java - 谁/什么实现了我可以直接使用的接口(interface)?

c - K&R 指向函数代码的指针

C 动态结构(malloc 和 free)

Delphi7,传递对象的接口(interface) - 释放对象时导致无效指针操作