3 ms·
Nillability is the biggest thing that drives me to write 'unidiomatic go': there are a few Optional libs around, they work ok. I write with the following rule:
by akdor1154 2y ago
Nillability is the biggest thing that drives me to write 'unidiomatic go': there are a few Optional libs around, they work ok.
I write with the following rule: if a pointer is passed, it shouldn't be nil. If it might be nil, code it as an Optional<> instead.
Un-golike but works great.
- hellcow 2y agoI define my own Null[T] for this purpose. There's sql.Null in the stdlib already, so that seems plenty go-like.
- autarch 2y agoWe have started doing this at work as well. It makes the code a lot easier to understand, and I think it's worth the small hassle that this entails (because without a `match` statement, dealing with an Option type is verbose).
- Neikius 2y agoThis is actually terrible. I tried that a while ago, but after a short while removed all of the Optional[] code and went back to pointers. Why? The default ser/des in go just cannot play. It instead works great with pointers. Using pointers that are nillable whenever I want to have an optional value. How did I solve the usability problem? I just introduced 2 simple methods: Or and Of. First one will resolve ptr to a value or default if nil (provided in param) and the second one will make a ptr from a value type. That is actually all you need! Don't have the code here or I'd post it but it's easy enough to make your own (with generics).
- jjdhxhbe 2y agoUsing a pointer in go can mean two things and I don't like it: - Value can be nil - Value is mutable It's neither possible to have a const but nilable value as well as it's not possible to have a non-nilable mutable value