optional

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 8 Imported by: 0

README

optional

Go Reference CI

Package optional provides Field[T], a value that is unset, null, or set. It works with encoding/json, encoding/json/v2, and database/sql, and has no dependencies.

go get github.com/tapp-ai/optional

Requires Go 1.24 or later.

Why

A JSON key or a database column can be in three states. A partial update (an HTTP PATCH, a JSON Merge Patch, a SQL UPDATE of some columns) has to tell them apart:

Request body Meaning Field[string]
{} Leave the nickname alone unset
{"nickname": null} Clear the nickname null
{"nickname": ""} Set the nickname to "" set to ""

Common Go types lose one of these states:

Type {} null ""
string "" "" ""
*string nil nil &""
optional.Field[string] unset null set to ""

Usage

Declare request fields as Field[T] and tag them with omitzero:

type UpdateUser struct {
	Name     optional.Field[string] `json:"name,omitzero"`
	Nickname optional.Field[string] `json:"nickname,omitzero"`
	Age      optional.Field[int]    `json:"age,omitzero"`
}

Decode, then apply each field according to its state:

var req UpdateUser
err := json.Unmarshal([]byte(`{"nickname":null,"age":41}`), &req)

if name, ok := req.Name.Get(); ok {
	user.Name = name
}

switch req.Nickname.State() {
case optional.StateNull:
	user.Nickname = nil
case optional.StateSet:
	user.Nickname = req.Nickname.Ptr()
}

Encoding gives back the same body, {"nickname":null,"age":41}. The unset Name field is left out because of omitzero.

Build values with Of, Null, or the zero value:

optional.Of("Ann")              // set to "Ann"
optional.Of(0)                  // set to 0, not null
optional.Null[string]()         // null
optional.Field[string]{}        // unset
optional.FromPtr(user.Nickname) // set to *p, or null when p is nil

API

Unset Null Set to v
State() StateUnset StateNull StateSet
IsUnset() / IsZero() true false false
IsNull() false true false
IsSet() false false true
Get() zero, false zero, false v, true
GetOr(fallback) fallback fallback v
Ptr() nil nil pointer to a copy of v
String() "unset" "null" v formatted with %v
Map(f, fn) unset null Of(fn(v))

Field[T] is a small value type. Copying it copies the value, and two fields compare with == when T is comparable.

When you switch on State(), the exhaustive linter reports a missing case.

Field is meant for data that crosses a boundary: request and response bodies, database rows, messages. For a function result that may be missing, return (T, bool) or *T.

JSON

Field Encoded with omitzero Encoded without it
unset key left out null
null null null
set to v v v
Input Decoded Field
key absent unset (the decoder never touches it)
null null
any other value set, or an error if the value doesn't decode into T

A set field whose value is a nil pointer, slice, map, or interface encodes as null, so it decodes as null. JSON can't tell the two apart. To mean "clear this", use Null[T]() rather than Of[*T](nil).

Use omitzero, not omitempty

omitzero calls IsZero(), which is true only for an unset field. Use it on every Field. omitempty is wrong in both JSON packages:

  • encoding/json never omits a struct, so an unset field is written as null.
  • encoding/json/v2 omits any value that encodes as null, so an explicit null disappears.
encoding/json/v2

On Go 1.27 and later, Field also implements MarshalJSONTo and UnmarshalJSONFrom. encoding/json/v2 uses them, and so does encoding/json, which runs on v2 from Go 1.27. On earlier versions, or with GOEXPERIMENT=nojsonv2, both packages use MarshalJSON and UnmarshalJSON. The two pairs behave the same, and CI tests every combination.

database/sql

Field[T] implements sql.Scanner and driver.Valuer.

Operation Result
Scan SQL NULL null
Scan a value set. Values convert the way database/sql converts into a plain T (for example int64 to int); one that can't convert returns an error.
Value of a set field its value. A T that implements driver.Valuer is used as is.
Value of a null field SQL NULL
Value of an unset field error ErrUnset

Value returns ErrUnset for an unset field because SQL can't say "not given". Writing NULL would silently clear a column the caller never meant to touch. To build a partial UPDATE, leave out columns whose field IsUnset(). Query builders that skip zero values by reflection, such as goqu's omitempty tag, skip unset fields automatically.

As with JSON, a set field holding a nil pointer writes NULL and scans back as null.

Development

go test -race ./...
GOEXPERIMENT=nojsonv2 go test -race ./...
go test -run='^$' -fuzz=FuzzJSON -fuzztime=1m

FuzzJSON checks that every JSON codec round-trips what it decodes, and that encoding/json and encoding/json/v2 decode a Field the same way.

License

MIT

Documentation

Overview

Package optional provides Field, a value that is unset, null, or set.

A JSON key or a database column can be in three states, and a partial update (an HTTP PATCH, a JSON Merge Patch, a SQL UPDATE of some columns) needs to tell them apart:

{}               Unset: the key is absent; leave the value alone.
{"name": null}   Null:  the key is null; clear the value.
{"name": "Ann"}  Set:   the key has a value; store it.

A pointer collapses the first two states, and a plain value collapses all three when the value is empty. Field keeps them apart, and keeps zero values such as 0, "", and false as real values.

The zero Field is unset. Tag Field struct fields with `json:",omitzero"` so unset fields are left out of encoded JSON.

For a function result that may be missing, return (T, bool) or *T instead. Field is for data that crosses a boundary.

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/tapp-ai/optional"
)

// UpdateUser is a PATCH body: each field can be left alone, cleared, or set.
type UpdateUser struct {
	Name     optional.Field[string] `json:"name,omitzero"`
	Nickname optional.Field[string] `json:"nickname,omitzero"`
	Age      optional.Field[int]    `json:"age,omitzero"`
}

func main() {
	var req UpdateUser
	_ = json.Unmarshal([]byte(`{"nickname":null,"age":0}`), &req)

	fmt.Println("name:", req.Name.State())
	fmt.Println("nickname:", req.Nickname.State())
	fmt.Println("age:", req.Age.State(), req.Age)

	out, _ := json.Marshal(req)
	fmt.Println(string(out))
}
Output:
name: unset
nickname: null
age: set 0
{"nickname":null,"age":0}
Example (Patch)

Apply a PATCH body to a stored record.

package main

import (
	"encoding/json"
	"fmt"

	"github.com/tapp-ai/optional"
)

type User struct {
	Name     string
	Nickname *string
	Age      int
}

// UpdateUser is a PATCH body: each field can be left alone, cleared, or set.
type UpdateUser struct {
	Name     optional.Field[string] `json:"name,omitzero"`
	Nickname optional.Field[string] `json:"nickname,omitzero"`
	Age      optional.Field[int]    `json:"age,omitzero"`
}

func main() {
	nick := "Annie"
	user := User{Name: "Ann", Nickname: &nick, Age: 40}

	var req UpdateUser
	_ = json.Unmarshal([]byte(`{"nickname":null,"age":41}`), &req)

	if name, ok := req.Name.Get(); ok {
		user.Name = name
	}
	switch req.Nickname.State() {
	case optional.StateNull:
		user.Nickname = nil
	case optional.StateSet:
		user.Nickname = req.Nickname.Ptr()
	}
	if age, ok := req.Age.Get(); ok {
		user.Age = age
	}

	fmt.Println(user.Name, user.Nickname, user.Age)
}
Output:
Ann <nil> 41

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrUnset = errors.New("optional: unset field has no SQL value")

ErrUnset is returned by Field.Value for an unset Field. SQL has no value for "not given", so an unset Field must be left out of the query rather than written as NULL.

Functions

This section is empty.

Types

type Field

type Field[T any] struct {
	// contains filtered or unexported fields
}

Field holds a value of type T that is unset, null, or set. The zero value is unset.

Field is a small value type: copying it copies the value, and two Fields can be compared with == when T is comparable.

func FromPtr

func FromPtr[T any](p *T) Field[T]

FromPtr returns a Field set to *p, or a null Field when p is nil.

Example
package main

import (
	"fmt"

	"github.com/tapp-ai/optional"
)

func main() {
	var nickname *string
	fmt.Println(optional.FromPtr(nickname).State())
}
Output:
null

func Map

func Map[T, U any](f Field[T], fn func(T) U) Field[U]

Map returns a Field set to fn(v) when f is set to v. An unset or null f gives an unset or null result, and fn is not called.

Example
package main

import (
	"fmt"

	"github.com/tapp-ai/optional"
)

func main() {
	name := optional.Of("Ann")
	length := optional.Map(name, func(s string) int { return len(s) })
	fmt.Println(length)
}
Output:
3

func Null

func Null[T any]() Field[T]

Null returns a Field that is explicitly null.

func Of

func Of[T any](v T) Field[T]

Of returns a Field set to v. Zero values such as 0, "", and false are set values, not null.

func (Field[T]) Get

func (f Field[T]) Get() (T, bool)

Get returns the value and true when f is set. Otherwise it returns the zero value of T and false.

Example
package main

import (
	"fmt"

	"github.com/tapp-ai/optional"
)

func main() {
	age := optional.Of(30)
	if v, ok := age.Get(); ok {
		fmt.Println(v)
	}
}
Output:
30

func (Field[T]) GetOr

func (f Field[T]) GetOr(fallback T) T

GetOr returns the value when f is set, or fallback otherwise.

Example
package main

import (
	"fmt"

	"github.com/tapp-ai/optional"
)

func main() {
	limit := optional.Null[int]()
	fmt.Println(limit.GetOr(50))
}
Output:
50

func (Field[T]) IsNull

func (f Field[T]) IsNull() bool

IsNull reports whether f is explicitly null.

func (Field[T]) IsSet

func (f Field[T]) IsSet() bool

IsSet reports whether f holds a value.

func (Field[T]) IsUnset

func (f Field[T]) IsUnset() bool

IsUnset reports whether f was never given a value.

func (Field[T]) IsZero

func (f Field[T]) IsZero() bool

IsZero reports whether f is unset. Encoding with `json:",omitzero"` uses it to leave unset fields out.

func (Field[T]) MarshalJSON

func (f Field[T]) MarshalJSON() ([]byte, error)

MarshalJSON encodes a set Field as its value, and a null or unset Field as null. Tag the struct field with `json:",omitzero"` to leave an unset Field out instead.

func (Field[T]) MarshalJSONTo

func (f Field[T]) MarshalJSONTo(enc *jsontext.Encoder) error

MarshalJSONTo is the streaming form of Field.MarshalJSON.

func (Field[T]) Ptr

func (f Field[T]) Ptr() *T

Ptr returns a pointer to a copy of the value when f is set, or nil otherwise.

func (*Field[T]) Scan

func (f *Field[T]) Scan(src any) error

Scan implements sql.Scanner. SQL NULL becomes a null Field. Any other value becomes a set Field, converted the way database/sql converts into a plain T; a value that can't be converted returns an error.

func (Field[T]) State

func (f Field[T]) State() State

State returns the state of f.

func (Field[T]) String

func (f Field[T]) String() string

String returns "unset", "null", or the value formatted with %v.

func (*Field[T]) UnmarshalJSON

func (f *Field[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes null as a null Field and any other value as a set Field. Decoders call it only for keys present in the input, so a struct field whose key is absent stays unset.

func (*Field[T]) UnmarshalJSONFrom

func (f *Field[T]) UnmarshalJSONFrom(dec *jsontext.Decoder) error

UnmarshalJSONFrom is the streaming form of Field.UnmarshalJSON.

func (Field[T]) Value

func (f Field[T]) Value() (driver.Value, error)

Value implements driver.Valuer. A set Field gives its value and a null Field gives SQL NULL. An unset Field returns ErrUnset, so a column that was never given a value is not overwritten with NULL by mistake.

type State

type State uint8

State is the state of a Field.

const (
	StateUnset State = iota // no value was given
	StateNull               // the value is explicitly null
	StateSet                // the field holds a value
)

func (State) String

func (s State) String() string

String returns "unset", "null", or "set".

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL