golang make struct T implement I 但不是 *T

标签 go

我有一个实现接口(interface) I 的结构 T,但我希望 *T 实现该接口(interface)。这可能吗?

也就是说,这应该可以正常编译:

var obj I = T{}

但这会产生一个编译错误:

var obj I = &T{}

原因是我的代码库中的一个常见错误是在预期只会使用 T 时意外使用 *T 作为某个接口(interface) I。

最佳答案

不可能。来自spec (强调我的):

A type may have a method set associated with it. The method set of an interface type is its interface. The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T).

关于golang make struct T implement I 但不是 *T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39522415/

相关文章:

amazon-web-services - 使用 aws-sdk-go/roleARN/queueARN (sqs) 获取消息

go - goroutine 没有输出

go - 无法在 Go 应用程序的另一个包中使用函数

date - 如何使用golang打印两个日期之间的特定日期?

go - 即使主域相同,跨源请求也被阻止

go.mod 使用没有标签的模块

go - BigTable 中多列的过滤器

ruby - Ruby 中的 AES-256-GCM 加密和 Golang 解密

regex - Go - 正则表达式操作

go - golang 是否没有文件结构?