Idiomatic optional struct fields: zero vs magic value vs bool

326 views
Skip to first unread message

Salvatore Domenick Desiano

unread,
Dec 11, 2023, 11:25:43 PM12/11/23
to golang-nuts
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.



Rick

unread,
Dec 12, 2023, 12:09:44 PM12/12/23
to golang-nuts
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.
Reply all
Reply to author
Forward
0 new messages