dealing with null (nil) values in nim
21.10.2023 2 min readI’ve been messing around with nim
for a little bit, and, for the most part, I quite like it. (I’m back to hating go
again for how verbose it is… don’t ask)
The only (minor) complaint that I have is that the language is, at times, poorly documentented (again, I have to say… could be a me problem).
Here’s what I was trying to do:
I wanted to fetch some JSON from a weather API. To use JSON in a way that makes nim
happy, you first have to unmarshal the data, which means specifying the field names and their respective types beforehand. But I quickly ran into a problem: the field I was trying to pick could be either a float
type or null
(I suppose the equivalent in nim
is nil
). I tried using an enum, but, that didn’t work (I was met with some error about Jstring
s). Anyway, it turns out that what you really want to do is use an option
type when there’s the possibility of something being nil
(or maybe there’s some other way, idk. This is what I found to work).
type
Daily = object
precipitation_probability_mean: seq[Option[int]]
And then try
to unpack it:
try:
forecast.daily.precipitation_probability_mean[idx].get()
# other code
except UnpackDefect:
discard