The real issue here is that it is not immediately obvious that this is actually an interface - one expects the second `err` to be *FormatError due to the signature - it happens to implement the error interface so it goes unnoticed.
Shadowing in a different scope allows it to work properly as well.
I admit that I've never actually run in to this issue in practice as I generally return custom errors as `error`, but I can see why it would confuse someone.
Totes.
Re:Griping about Go
by hombre_fatal on Thursday February 07, 2019 @06:20PM
(#19109693)
> To avoid encountering this issue, return `error`, not something else.
But best practice is to return concrete types.
Also, `err` is just an example in this minimal snippet. It can happen with any variable.
Here's a similar snippet: https://play.golang.org/p/WKPey_PL_ht -- Looks impossible to crash. :P
Spoiler: it's a boxed null, not a null.
Best practice is to return concrete types for everything, but error is one of those "special" cases that people tend to return an `error` for, IME.
You can always unwrap it via type assertion, however ugly that may be.
Re:Griping about Go
by thegeekpirate on Thursday February 07, 2019 @06:31PM
(#19109753)
> But best practice is to return concrete types.
You're taking this as an absolute when you shouldn't be. There's plenty of places in the standard library that don't follow this "rule".
The value ends up being a non-nil interface value that holds nil.
To avoid encountering this issue, return `error`, not something else.
https://play.golang.org/p/jZ5Fa24bbUz