7 ms·
"The real problem is that they imported the concept of null/nil being a value of every type from C." While I agree that's a problem, it's mostly a separate pro
by jerf 4y ago
"The real problem is that they imported the concept of null/nil being a value of every type from C."
While I agree that's a problem, it's mostly a separate problem to the nil interface vs. interface containing a nil. The "nilness" provides a cognitively-convenient hook, especially with the attractive nuisance of the whole issue of nil/null in general, but the root cause of this particular issue is really "putting things into interfaces that don't fulfill the contract of the interface", which as I show in my post, doesn't require a nil anywhere in sight to do it.
When you stop doing that, this whole interface nil vs. containing a nil problem goes away. Basically, in Go code, you should never be trying to penetrate an interface value to see if it contains a nil. If you're doing that, the error occurred when the value you are examining was created, not at the point of use.
In fact, stop putting values that can't implement interface contracts into interface values and other code issues just go away, too. Not just in Go, either. Most large dynamically-typed language programs I've ever worked in are also shot through with this exact issue, it's just less visible because the compiler doesn't help you with the interfaces. They're still there, though. Just in the dark.
- ok_dad 4y agoEven as a beginner in Go, I somehow internalized that if you want a value to be `nil`, use a "bare `nil`" rather than a concrete value initialized to `nil`. I don't know why you would want to initialize something on the heap, like in the article, if you didn't plan to use it later. Maybe in the most extreme case you might want to prepare an error object before the processing occurs, but even then I have never seen any Go tutorial that didn't return a "bare `nil`" for the `(err error)` return value if there was no error being returned. I guess people coming to Go from other languages sometimes don't look at the tutorials, or perhaps don't try and understand the language's "best practices"?
- masklinn 4y agoIn real code, the problem would usually occur not because you want a value to be nil but because you’re converting a value you already have to an interface. And that value happened to be a pointer which is nil.
- t8sr 4y agoArguably the most common line of code in Go, ‘if err != nil’ is doing what you’re saying you should never do in the language: check if an interface value is nil. (And, in fact, care must be taken when returning custom error types precisely because of the typed nil issue.) So I don’t think the authors of the language see it the same way you do. (FWIW I was also a Go style reviewer working with the Go team for a few years, and I’ve never heard this idea from them in that time.)