"Pointers to primitives let you represent the absence of a value."


1. Optional / Nullable Values

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
}

2. JSON omitempty

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.


3. Partial Updates (PATCH APIs)

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.

These are now distinguishable!


4. Database NULL Handling