猿问

如何使用 Nil Receiver 处理方法?

type Product struct {

    productName string

}


func (p *Product) GetProductName() string {

    return p.productName

}

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

  1. 不要处理它,让它恐慌

  2. 检查 nil,如果为真则返回零值

  3. 使用有意义的消息检查 nil 和 panic

  4. 检查 nil 并增强在 nil 上返回错误的方法

  5. 其他

  6. 这真的取决于

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


慕桂英3389331
浏览 159回答 1
1回答

撒科打诨

不要处理它,让它恐慌您可以在 go 标准库中查看示例。例如,在net/http包中,有以下内容:func (c *Client) Do(req *Request) (*Response, error) {    return c.do(req)}而且,另一个例子来自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:])}
随时随地看视频慕课网APP

相关分类

Go
我要回答