Go Desperately Needs Nil Safe Types
If you’ve worked with Go before, you’ve probably seen this runtime error.
1 | panic: runtime error: invalid memory address or nil pointer dereference |
The current solution is checking thevar != nil
before using the var, but forgetting to do that means your program will crash. That means this simple programmer error could take down your whole server. Hopefully you catch these errors with tests before they reach production. However, we’re not machines so inevitably we won’t catch some of these until our end users encounter an error in production.
Go should have types that can never be nil
Jelte Fennema already proposed a solution over 3 years ago:
The idea is really simple and is also used by Rust and C++: add a pointer type that can never be nil.
Jelte compares Go to Rust, saying that safe Rust doesn’t have nil-able pointers.
However, I think comparing Go to Swift fits better because Go will never get rid of nil pointers.
Swift
Swift has two types of variables: Optionals and Non-Optionals. Optional means nullable.
Non-optional variables in Swift are guaranteed to never be nil. Your function no longer needs to check it’s arguments for nil if you declare your arguments non-optional. Imagine deleting all those duplicate if myarg == nil
in all your functions with the guarantee your inputs won’t ever be nil!
Conclusion
Go2 has several open proposals for non-nil types, but nothing seems to be decided upon yet. Hopefully they don’t dismiss this lightly. In my opinion, this is the only thing holding Go back from competing with Rust, Swift, TypeScript and other languages with non-nullable types.
Published on Java Code Geeks with permission by Priyanka Sharma, partner at our JCG program. See the original article here: Go Desperately Needs Nil Safe Types Opinions expressed by Java Code Geeks contributors are their own. |