在空结构体上定义方法接收器是否是一种不好的做法?

huangapple go评论98阅读模式
英文:

Is it a bad practice to define a method receiver on an empty struct?

问题

我看到一些包含在空结构体上的方法接收器的代码。在Go语言中,这是一种不好的编码实践吗?

  1. type Example struct {
  2. // 没有属性
  3. }
  4. func (e *Example) DoSomething() error {
  5. return nil
  6. }

我应该建议他使用带有什么理由的Go函数替代呢?

  1. func DoSomething() error {
  2. return nil
  3. }

在Go语言中,将方法接收器绑定到空结构体是一种常见的做法,被称为"接口型方法"。这种做法可以用来实现接口,但是在没有任何属性的结构体上使用方法接收器可能会让代码看起来有些奇怪。相比之下,将函数定义为包级别的函数可能更加清晰和简洁。因此,我建议他使用Go函数代替方法接收器,这样可以避免不必要的结构体定义。

英文:

I saw some code that contains a method receiver on an empty struct. Is it a bad coding practice in Go?

  1. type Example struct {
  2. // no attribute
  3. }
  4. func (e *Example) DoSomething() error {
  5. return nil
  6. }

Shall I recommend him to use Go function instead, but with what justification?

  1. func DoSomething() error {
  2. return nil
  3. }

答案1

得分: 2

这是要翻译的内容:

这是有道理的,例如,如果你想要实现一个接口,你就需要一个类型来做到这一点。在这种情况下,一个空的结构体可能是必要的。

  1. type SomethingDoer interface {
  2. DoSomething() error
  3. }
  4. // Example 实现了 SomethingDoer 接口。
  5. type Example struct {
  6. // 没有属性
  7. }
  8. func (e *Example) DoSomething() error {
  9. return nil
  10. }
  11. // 有时会使用下面这样的语句来断言一个类型实现了特定的接口。
  12. var _ SomethingDoer = &Example{}

此外,正如 @NotX 提到的,有时候你正在构建一个更大的东西,你可能会立即将其作为一个类型,因为你知道在后面你想要添加状态。我个人避免这种"防御性编程",只在需要时才添加类型。但是风格和观点各不相同,所以这并不罕见。

英文:

It can make sense, e.g. in case you want to implement an interface, you need a type to do it. An empty struct might be necessary in that case.

  1. type SomethingDoer interface {
  2. DoSomething() error
  3. }
  4. // Example implements the SomethingDoer interface.
  5. type Example struct {
  6. // no attribute
  7. }
  8. func (e *Example) DoSomething() error {
  9. return nil
  10. }
  11. // A line like the following is sometimes used to assert
  12. // that a type implements a specific interface.
  13. var _ SomethingDoer = &Example{}

Also, as mentioned by @NotX, sometimes you are in the middle on constructing a larger thing and you might make it a type right away because you know that down the line you want to add state to it. I personally stay away from this kind of "defensive programming" and would add a type only when needed. But styles and opinions differ, so it is not uncommon.

huangapple
  • 本文由 发表于 2023年7月14日 00:01:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76681350.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定