4 ms·
You are still speaking as if an interface containing a nil is the same as a nil interface. They are not. ∗MyError(nil) as an error value is perfectly valid. It
by jerf 6y ago
You are still speaking as if an interface containing a nil is the same as a nil interface. They are not. ∗MyError(nil) as an error value is perfectly valid. It means there is an error, and whatever created that value is promising that you can call .Error() on the resulting value and get a string. If you get a panic instead of a string, the code that made that promise is where the bug is, not the code that called .Error()... and in Go, it is perfectly possible for that nil to produce a string perfectly validly. Calling methods on a nil is not invalid Go. That is a concept ported over from C++ or similar languages inappropriately. It is as wrong as worrying that you can't create a value on the stack in a function and return it. Go does not work that way.
Until you correct your understanding, you will continue to find Go frustrating. nil and invalid are not the same thing. This is not a matter of opinion; it is how the language works. As long as you persist in thinking otherwise, you will remain confused.
If you checked whether err is nil by checking the interface value, and then penetrating the interface to see if the underlying concrete type is a pointer and than pointer is nil, that is a bug in the code doing that. You should never do that. It is never correct. It is objectively wrong to think of them as the same thing and to treat them the same, because they are not.
The correct solution is what I outlined; do not create the lying interface values in the first place. Then they can not propagate through your code and mess you up.
I'm not trying to debate whether Go is "right" or "wrong" here. It is perfectly acceptable to come to a correct understanding of how Go works and still think it is not the best way to build the language. Personally I'd still be happy to get non-nillable pointers, in the same way C# managed to add them later, so you can put me in that category myself. But you still have an incorrect understanding of how Go works, and I'm writing this not to defend Go but to try to save you that frustration. However, if you keep resisting the correct understanding, you will continue to be confused and frustrated and write bugs.