加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 19:20:51 所属栏目:大数据 来源:网络整理
导读:我有一个功能 func doStuff(inout *interface{}) { ...} 该功能的目的是能够将任何类型的指针视为输入. 但是当我想用一个结构体的指针来调用它时,我有一个错误. type MyStruct struct { f1 int} 调用doStuff时 ms := MyStruct{1}doStuff(ms) 我有 test.go:38
我有一个功能
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{}) {
   ...
}

见this example:

ms := MyStruct{1}
doStuff(&ms)
fmt.Printf("Hello,playground: %vn",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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读