3 ms·
To avoid the nil pointer dereference panic, could you use an idiom borrowed from Go's map implementation? A library could take advantage of multiple assignment
by drbawb 14y ago
To avoid the nil pointer dereference panic, could you use an idiom borrowed from Go's map implementation?
A library could take advantage of multiple assignment, a la maps:
`i, ok := m["route"]`
If the map has no entry for key "route", i will be the zero type [e.g: an empty string], and OK will be a bool indicating that the key wasn't found in the map.
So in a SQL library it might look something like
`func (s Statement) GetString(columnNum int) string,bool`
Called as: `str,ok := s.GetString(i)`
At least this way your program won't panic() if you forget to check that string != nil and dereference *string, but you still retain the information that the string is nil.
- chimeracoder 14y agoYes, that's actually more or less what NullString does. It's a struct that contains two fields: String and Valid (a boolean). It also implements a couple of other interfaces, but at its core, it's what you describe. Functionally, they're basically the same thing - it's only a syntactic difference whether you check whether a pointer is nil vs. checking whether a boolean is false. At some point, you either have to do a check or coerce a null value into a reasonable value. (Or, I guess, just risk it!). Functional programming purists may cringe at the analogy, but this is is all more or less the same functionality as Scala's 'Option' monad - it just depends on how you want to express it. The only difference is that the Go compiler doesn't force you to check against nil before dereferencing, but if you want to ensure the safety before converting the database value to a String and forgetting about it, then the struct will do that.