Comment by TheDong
5 months ago
On multiple types, there's another reason there's multiple types.
Imagine a function that looks like:
addr, err := netip.ParseAddrPort(input)
if err != nil { return err }
err = makeConnection(addr)
if err != nil { return err }
The caller of this function will now want to distinguish between "Did we fail to parse input, or did we fail to do networking".
The way to do that is to have `netip.ParseAddrPort` failures return a different error type than other methods, but the "idiomatic" go code above doesn't wrap the error with an additional type, so the caller can't distinguish between a network error (many of which are also just 'errors.New'), and a netip parse error (all of which are 'errors.New').
Pushing that responsibility onto the callers seems silly, and like a footgun, especially when several other packages do have typed errors that mean the caller can successfully identify the error without having to do verbose explicit wrapping.
> The way to do that is to have `netip.ParseAddrPort` failures return a different error type than other methods
No. Absolutely not. If you leave the callers of this hypothetical function to rely on the errors of the functions it calls, even if we assume those functions were written by an infallible deity, you've created a coupling that now binds you to the implementation forevermore. That's just plain reckless behaviour.
Return your own errors. I know it takes a tiny amount of extra thinking to figure out what types are relevant to your function, but is unquestionably worthwhile and would still be worthwhile even if all the functions you call were designed by an infallible entity.
> but the "idiomatic" go code
You're really stretching the use of idiomatic here. Not ever has that been considered idiomatic Go. The Go community has always been clear that you should never, ever write code like that. It is so painfully horrid for so many reasons that it could never be considered idiomatic.