我有一个实现接口(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/