Go developers build 'opt' library to fix sql.Null[T]'s permanent JSON incompatibility
Go 1.22 introduced the generic sql.Null[T] type for handling nullable SQL values, but the type produces malformed JSON output, serializing as a struct with 'V' and 'Valid' fields rather than a plain value or null. A proposal to add JSON marshaling support to sql.Null[T] was officially closed as infeasible, as Go's policy prohibits adding marshal methods to types that already have a default struct-based marshaling behavior. Existing workarounds such as pointer types and the popular guregu/null package each carry trade-offs, including pointer overhead, legacy API constraints, and an inability to distinguish between an absent field and a null field. Developers at coregx responded by building the 'opt' library for Go 1.24+, which provides nullable types that work correctly with both JSON and SQL without pointer allocation or boilerplate code. A key feature called Field[T] introduces three distinct states — absent, null, and value — enabling precise handling of PATCH API requests where distinguishing an omitted field from an explicitly nulled one is critical.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in