type Product struct {
productName string
}
func (p *Product) GetProductName() string {
return p.productName
}
In Go, how should one typically handle a scenario where the receiver on a method is nil and the method logic itself yields no error (e.g a getter)?
I lean towards #1, but figure that while #3 is a bit verbose it could make debugging easier. My thoughts are the calling code should be testing for nil and know what to do in such a scenario. That returning an error on a simple getter method is too verbose.
Don't handle it, let it panic
You can see examples in the go standard library. For example, in the net/http
package, there is the following:
func (c *Client) Do(req *Request) (*Response, error) {
return c.do(req)
}
And, another example from 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:])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With