type Product struct { productName string}func (p *Product) GetProductName() string { return p.productName}在 Go 中,通常应该如何处理方法的接收者为 nil 并且方法逻辑本身不会产生错误(例如 getter)的情况?不要处理它,让它恐慌检查 nil,如果为真则返回零值使用有意义的消息检查 nil 和 panic检查 nil 并增强在 nil 上返回错误的方法其他这真的取决于我倾向于#1,但认为虽然#3 有点冗长,但它可以使调试更容易。我的想法是调用代码应该测试 nil 并且知道在这种情况下该怎么做。在简单的 getter 方法上返回错误太冗长了。
1 回答

撒科打诨
TA贡献1934条经验 获得超2个赞
不要处理它,让它恐慌
您可以在 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:])
}
- 1 回答
- 0 关注
- 158 浏览
添加回答
举报
0/150
提交
取消