4 ms·
I've usually seen this handled by having everything be a pointer, the default value of the pointer is nil. You can also use the SQL values.
by X6S1x6Okd1st 5y ago
I've usually seen this handled by having everything be a pointer, the default value of the pointer is nil. You can also use the SQL values.
- the_gipsy 5y agoIsn’t it insane to change your types to accommodate this? You have to change all fields accesses, it behaves differently, you lose non-nullability…
- shp0ngle 5y agoWell that's go for you. Go is simple and "default case" which is simple and works for most cases... and then you have edge cases where you need to bend over backwards. As an exercise, try to use comma (",") in JSON field name.
- autarch 5y ago> Isn’t it insane to change your types to accommodate this? Welcome to Go! This was a real pain for us at my last job, where we used go-swagger to generate REST API code. All the generated structs had pointers for _non-optional_ fields so it could also check that they were populated. Meanwhile, optional fields were not pointers because they could use the default value. So then we ended up with lots of code doing checks for `is X nil` all over the place. Many of those wouldn't be needed in normal usage, since a nil value would be rejected by the validator earlier, but we also sometimes needed to make these structs by hand and pass them around. All of this is necessary because of the lack of generics. With generics you can solve this with things like an `Option<T>` type, like Rust does.
- bpicolo 5y agoPretty excited for Go 1.18 for that reason! Will likely take some time for the ecosystem to shuffle out good solutions for different bits, though
- the_gipsy 5y agoYea exactly, pointers id allowing nils, which I don’t want to conflate with omitting either. In the end what I did is parse the JSON-string twice, once more with a “checkjson” library that tells me about missing fields.
- bpicolo 5y agoDon't you do that in rust too? You'd be working with Option<T> instead of T.
- couchand 5y agoThe critical difference is that an Option<T> is not a T, but a nil pointer is still a pointer. The stylistic difference is that the Rust type is semantic: your optional values are Options. The Go type is silly: why does being a pointer (which is allowed to be nil) imply required?
- mcintyre1994 5y agoOption<Int> is a really good way to describe a field that if present is an int, but may not be present, though. Pointer isn't.
- ironmagma 5y agoI don't think so. Speaking as a Rust dev, if you want to do anything slightly different from how things currently work, you need to change the types, which can be a major hassle.