将结构指针转换为 Golang 中的接口指针 [英] Cast a struct pointer to interface pointer in Golang

查看:43
本文介绍了将结构指针转换为 Golang 中的接口指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能

func doStuff(inout *interface{}) {...}

此函数的目的是能够将任何类型的指针视为输入.但是当我想用结构的指针调用它时,我有一个错误.

type MyStruct struct {f1 整数}

当调用doStuff

ms := MyStruct{1}doStuff(&ms)

我有

test.go:38: 不能在 doStuff 的参数中使用 &ms (type *MyStruct) 作为类型 **interface {}

如何将 &ms 转换为与 *interface{} 兼容?

解决方案

没有指向接口的指针"这样的东西;(从技术上讲,您可以使用一个,但通常您不需要它).

如:

ms := MyStruct{1}doStuff(&ms)fmt.Printf(你好,操场:%v
", ms)

输出:

你好,游乐场:{1}


由于 newacct 提到了 在评论中:

<块引用>

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

在这种情况下,接口是空接口,因此它无论如何都接受所有类型,但仍然如此.

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
", 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆