go - 在 golang 中,如果其中一个方法必须具有指针接收器,是否有必要将一种类型的所有方法更改为具有指针接收器?

标签 go interface

我正在学习 golang,我对在值或指针上定义方法有点困惑。如 doc 中所述:

Next is consistency. If some of the methods of the type must have pointer receivers, the rest should too, so the method set is consistent regardless of how the type is used. See the section on method sets for details.

如果我有一个类型 T,它需要实现几个接口(interface)。一个接口(interface)有方法需要使用指针接收器,而另一个接口(interface)中的方法可以很好地使用值接收器。是否需要将所有接口(interface)中的所有方法更改为具有指针接收器?如果是,为什么?

最佳答案

视情况而定:)

你的类型 T 有两个方法集:

  • receiver (t T) 的方法集,它是定义的所有方法 接收器(t T)

  • receiver (t *T) 的方法集,即所有具有 receiver (t *T) 的方法 AND 所有具有 receiver (t T) 的方法

    <

所以如果你有一个满足 T 的接口(interface),它也满足 *T。 (但反之则不然)

因此,如果您必须向类型添加 *T 接收器方法以满足接口(interface),您不需要将其他方法接收器更改为 *T,但您必须注意现在只有 *T 满足该接口(interface),而 T 和其他接口(interface)可能都满足。

type fooer interface {
    foo()
}

type barer interface {
    bar()
}

type T struct {}

func (t T)foo(){}

func (t *T)bar(){}

var _ fooer = T{}  // ok
var _ barer = T{}  // NOT OK - won't compile
var _ barer = &T{} // ok
var _ fooer = &T{} // ok

令人困惑?是的,可以。因此,尽管您不必必须更改所有方法以使用指针接收器,但如果您这样做,它会更加一致且不易混淆 - 这样您就知道您总是在处理 *T代码 - 这似乎是大多数人所做的。

关于go - 在 golang 中,如果其中一个方法必须具有指针接收器,是否有必要将一种类型的所有方法更改为具有指针接收器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49937748/

相关文章:

GO函数参数中数组的通用类型

java - Java中只有子类重写接口(interface)方法

java - 为什么在这种情况下使用接口(interface)而不是抽象类?

go - 在 Golang 中渲染页面后如何发送 websocket 数据?

go - Go 中的错误处理在 http 响应中返回空错误对象

c# - 如何在类和派生类之间使用接口(interface)?

java - 为什么 Java 中没有最终接口(interface)?

java - 如何找到在给定类中实现其方法的 Java 接口(interface)?

go - 创建实现接口(interface)的结构实例的函数

go - 确定从 go 函数返回的内容