type Product struct {
productName string
}
func (p *Product) GetProductName() string {
return p.productName
}
Run Code Online (Sandbox Code Playgroud)
在 Go 中,通常应该如何处理方法上的接收者为零且方法逻辑本身不产生错误(例如 getter)的情况?
我倾向于#1,但认为虽然#3 有点冗长,但它可以使调试更容易。我的想法是调用代码应该测试 nil 并知道在这种情况下该怎么做。在简单的 getter 方法上返回错误太冗长了。
别管它,让它惊慌
您可以在 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)