Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle method with Nil Receiver?

Tags:

methods

null

go

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)?

  1. Don't handle it, let it panic
  2. Check for nil and return zero value if true
  3. Check for nil and panic with meaningful message
  4. Check for nil and enhance the method to return error on nil
  5. Other
  6. It really depends

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.

like image 377
Owl Avatar asked Sep 04 '25 17:09

Owl


1 Answers

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:])
}
like image 86
Shang Jian Ding Avatar answered Sep 07 '25 16:09

Shang Jian Ding