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

时间:2014-11-27 21:05:33

标签: 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{}兼容?

1 个答案:

答案 0 :(得分:50)

没有指向接口的"指针" (从技术上讲,你可以使用一个,但通常你不需要它。)

如" what is the meaning of interface{} in golang?"中所示,interface是一个包含两个数据字的容器:

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

interface

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

  

将指针直接传递给接口是有效的,因为如果MyStruct符合协议,那么*MyStruct也符合协议(因为类型的方法集包含在其指针类型中#39;方法集)。

     

在这种情况下,接口是空接口,因此它仍然接受所有类型,但仍然。