In my opinion, this depends on exactly one thing: I nil is expected to be a
valid value (and I need to dereference it to implement that valid
behavior), I will check for nil to trigger that behavior. An example is a
linked list or tree data-structure, where calling a method on nil can
signal "end of list" and simplify code, e.g.:
https://go.dev/play/p/3iBnERuId_v

Otherwise, I don't check. If nil is not an expected value, calling a method
on a nil-pointer is a bug and it will panic as soon as it is dereferenced.
Panicing on a bug is the correct behavior. Usually, there isn't anything do
to but panic in that case anyways - I could do `if p == nil { panic("nil
pointer") }`, but that doesn't add any benefit, the panic will happen
either way.

Some people will advocate to return an error when calling a method on a
nil-pointer which doesn't expect that, if it already returns an error (and
letting it panic otherwise). Personally, I strongly disagree with this
philosophy. To me, a panic is meant to be communicated to the *programmer*,
to debug (and hence it produces a stacktrace), while an error is meant to
be communicated to the *user* of a program. In particular, an error should
be fixable without touching the program. "File config.json does not exist"
is a clear error, which the user of a program can interpret and fix and
which is not dependent on the internal validity of the program. "(*Foo).Bar
called on a nil-pointer" is something they can do nothing about -
especially not without a stack trace". Hence, returning an error on a
nil-pointer is converting a useful signal into a useless one, frustrating
both the user and the programmer, who has then to try and fix a bug,
without any debugging-context.

On Fri, Nov 26, 2021 at 5:39 AM shinya sakae <sakashin10291...@gmail.com>
wrote:

> Hi.
> I've been using Go for a while now, and I've noticed something.
> Do pointer receiver methods need to be checked for nil?
> In the standard package, it may or may not be checked.
> I'd like to hear your opinions.
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/8bada92b-f179-4133-adcf-0cf971671b00n%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/8bada92b-f179-4133-adcf-0cf971671b00n%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAEkBMfGbTffrweW-Kjqj5ZyvrpTzXiwcRWeXcyy-Ct-o8NowGA%40mail.gmail.com.

Reply via email to