"Pointers to primitives let you represent the absence of a value."
Problem: Can't distinguish "zero value" from "not set":
type Config struct {
Port int // Is 0 "not set" or intentionally 0?
Enabled bool // false = not set, or explicitly disabled?
}
Solution:
type Config struct {
Port *int
Enabled *bool
}
func (c *Config) GetPort() int {
if c.Port != nil {
return *c.Port
}
return 8080 // Default
}
type User struct {
Name string `json:"name"`
Age *int `json:"age,omitempty"`
Email *string `json:"email,omitempty"`
}
u1 := User{Name: "Alice", Age: intPtr(25)}
u2 := User{Name: "Bob", Age: nil}
json.Marshal(u1) // {"name":"Alice","age":25}
json.Marshal(u2) // {"name":"Bob"} — age omitted!
Without pointers, zero values (0, false, "") are still included.
type UpdateUserRequest struct {
Name *string
Age *int
Email *string
}
Pattern: Check each field for nil before updating. Only non-nil fields get written to the database.
{"age": 0} → sets age to zero (pointer is non-nil, value is 0){} → leaves age unchanged (pointer is nil)These are now distinguishable!