Nullable JSON Fields as Go Pointers
Learn when and why to use pointer types (*string, *int) for nullable JSON fields in Go structs. Covers nil vs zero value semantics.
Detailed Explanation
Using Pointers for Nullable JSON Fields
JSON supports null as a value, but Go does not have a null type for primitives. The solution is to use pointer types, where nil represents JSON null.
The Problem
{ "name": "Alice", "age": null, "score": 0 }
With a plain int field, both null and 0 unmarshal to 0, making them indistinguishable.
The Solution: Pointers
type Player struct {
Name string `json:"name"`
Age *int `json:"age"`
Score *int `json:"score"`
}
Now:
null→Ageisnil0→Scorepoints to anintwith value0- missing key →
Ageisnil
Checking Pointer Fields
if player.Age != nil {
fmt.Printf("Age: %d\n", *player.Age)
} else {
fmt.Println("Age: not provided")
}
When to Use Pointers
Use pointers when:
- The API sends
nullfor a field and that differs from the zero value - You need to distinguish "field absent" from "field is zero"
- Building PATCH request bodies where only changed fields are sent
Avoid pointers when:
- The field is always present and non-null
- The zero value is not a valid value in your domain
- Simplicity matters more than null-safety
Combining with omitempty
Age *int `json:"age,omitempty"`
This omits the field when the pointer is nil, includes it (even as 0) when non-nil.
Performance Note
Pointers add a small heap allocation per field. For high-throughput services processing millions of objects, benchmarking may reveal that avoiding unnecessary pointers improves performance.
Use Case
Database-backed APIs often return null for columns with no value. Using pointer fields in your Go structs ensures you can distinguish between a user who set their age to 0 and one who never set it.