在方法中使用空结构作为接收器

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

empty struct as receiver in method

问题

在这里使用空结构体Asn1的好处是可以将Encode()和Decode()方法与Asn1类型绑定在一起,形成一个组合。尽管在这些方法中没有直接使用接收者"a",但是通过将方法与Asn1类型关联,可以更好地组织代码和逻辑。

如果不使用空结构体,而是直接定义Encode()和Decode()方法,那么调用这两个方法时就需要使用函数名来调用,而不是通过实例来调用。这样会使代码调用变得更加复杂,需要显式地传递参数。

使用空结构体作为接收者,可以将Encode()和Decode()方法作为Asn1类型的方法,使得调用更加简洁和直观。例如,可以像下面这样调用:

asn1 := new(Asn1)
message, err := asn1.Decode(payload)

这样的调用方式更符合面向对象的编程风格,使代码更易读、易懂。

英文:

what is the benefit of using empty struct Asn1 here?
Moreover, we are using receiver "a" in Encode() and Decode() methods, but never used in those.
So what is the use here?

type Asn1 struct {} // empty struct

func (a *Asn1) Encode(message RmrPayload) ([]byte, error) {
        buffer := new(bytes.Buffer)
        asn1 := gob.NewEncoder(buffer)
        if err := asn1.Encode(message); err != nil {
                return nil, err
  }
        return buffer.Bytes(), nil 
}

func (a *Asn1) Decode(data []byte) (RmrPayload, error) {
  message := new(RmrPayload)
  buffer := bytes.NewBuffer(data)
        asn1 := gob.NewDecoder(buffer)
        if err := asn1.Decode(message); err != nil {
                return RmrPayload{}, err 
  }
        return *message, nil 
}

making it receiver makes complicated calling Encode() and Decode() method like below

  asn1 := new(Asn1)
  message, err := asn1.Decode(payload)

why we can not define these two methods without empty struct and call simply as

message, err := Decode(payload)

答案1

得分: 3

在空结构体上定义方法的主要原因是为了满足接口的要求。裸函数不能以这种方式使用。

英文:

The main reason to define methods on an empty struct is to satisfy an interface. Bare functions cannot be used this way.

huangapple
  • 本文由 发表于 2022年9月22日 18:26:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/73813070.html
匿名

发表评论

匿名网友

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

确定