For my work, the most common place I handle this is POST JSON => Unmarshal 
to Go struct =-> SQL query.

When unmarshaling a JSON body with possibly null fields, like you, I 
declare the corresponding Go struct fields as pointers. And have wrappers 
IfNullString(), IfNullInt() etc to convert to a sql.NullString etc that may 
be used as the argument to the SQL query. I don't consider it magical.

On Monday 11 December 2023 at 20:25:43 UTC-8 Salvatore Domenick Desiano 
wrote:

> I've never really been at peace with using zero values to indicate that a 
> struct field is absent. I use nil (fieldA *int, fieldB *string, etc.) if I 
> have to (I'm looking at you, JSON), but in most other cases the "nil" 
> approach feels dangerous (panics) and magical.
>
> Does anyone have an approach they feel comfortable with? At various points 
> I've thought about:
>
>    - bool guard (HasField bool, Field int)
>    - pointer (Field *int)
>    - zero value (Field int, absent if 0)
>    - magic value (Field int, absent if MaxInt)
>    - private values (func Field() (int, bool))
>    - enum guard (Mode StructMode, Field int)
>    - generic optional (Field Optional[int])
>
> I prefer idiomatic approaches but they are all error prone because 
> checking the guard is not required programmatically. I generally use the 
> bool guard and sometimes pointer. I feel like I should be more comfortable 
> with the zero value but it doesn't always work.
>
> What say you, oh Go Wizards?
>
> -- Salvatore
> smile.
>
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/01ae1eff-ebf5-4089-92e0-2484bf15a2a4n%40googlegroups.com.

Reply via email to