如何处理带有 Nil Receiver 的方法?

Owl*_*Owl 4 methods null go

type Product struct {
    productName string
}

func (p *Product) GetProductName() string {
    return p.productName
}
Run Code Online (Sandbox Code Playgroud)

在 Go 中,通常应该如何处理方法上的接收者为零且方法逻辑本身不产生错误(例如 getter)的情况?

  1. 别管它,让它惊慌
  2. 检查是否为 nil,如果为 true,则返回零值
  3. 使用有意义的消息检查 nil 和panic
  4. 检查 nil 并增强方法以在 nil 上返回错误
  5. 其他
  6. 这真的取决于

我倾向于#1,但认为虽然#3 有点冗长,但它可以使调试更容易。我的想法是调用代码应该测试 nil 并知道在这种情况下该怎么做。在简单的 getter 方法上返回错误太冗长了。

Sha*_*ing 6

别管它,让它惊慌

您可以在 go 标准库中查看示例。例如,在net/http包中,有以下内容:

func (c *Client) Do(req *Request) (*Response, error) {
    return c.do(req)
}
Run Code Online (Sandbox Code Playgroud)

并且,另一个例子encoding/json:

// Buffered returns a reader of the data remaining in the Decoder's
// buffer. The reader is valid until the next call to Decode.
func (dec *Decoder) Buffered() io.Reader {
    return bytes.NewReader(dec.buf[dec.scanp:])
}
Run Code Online (Sandbox Code Playgroud)