←back to thread

Go subtleties

(harrisoncramer.me)
234 points darccio | 1 comments | | HN request time: 0.226s | source
Show context
rowanseymour ◴[] No.45666258[source]
Ah the old nil values boxed into non-nil interfaces. Even after 8 years writing go code almost every day this still bites me occasionally. I've never seen code that actually uses this. I understand why it is the way it is but I hate it.
replies(4): >>45666614 #>>45666792 #>>45666859 #>>45669163 #
kitd ◴[] No.45666859[source]
The advice I've read (and follow) is always to return values, not interfaces, from functions and test for nil against them. That IME tends to nip the majority of nil interface problems in the bud.
replies(4): >>45667017 #>>45667105 #>>45667244 #>>45667694 #
1. Magnolia9438 ◴[] No.45667694[source]
On the happy path downstream, yes, and it does work really well. But the error flow back upstream flips that, as errors are returned as, often nested, interfaces.

This is fine for a lot of general purpose code that exits when running into problems. But when errors are an expected part of a long lived process, like an API, it’s painful to build logic around and conditionally handle them.

The ergonomics of errors.Is and As are pretty bad and there doesn’t seem to be a clear indication as when to expect a sentinel, concrete, or pointer to a concrete error.

All that to say, I think Go’s errors really illustrate the benefit of “return values, not interfaces”. Though for errors specifically, I’m not sure you could improve them without some pretty bad tradeoffs around flexibility.