optional

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: Apache-2.0 Imports: 2 Imported by: 0

Documentation

Overview

Package optional provides Optional[T], a tri-state value for PATCH-style request bodies, where "field absent", "field explicitly null" and "field set to a value" mean different things:

type UserPatch struct {
	Name  optional.Optional[string] `json:"name,omitzero"`
	Phone optional.Optional[string] `json:"phone,omitzero"`
}

Decoding {"phone": null} leaves Name as None (do not touch the column) and sets Phone to Null (clear the column). The zero value of Optional[T] is None, so an absent JSON field needs no special handling.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Optional

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

Optional holds one of three states: None (absent), Null (explicitly null) or Some(v) (a value). The zero value is None.

func None

func None[T any]() Optional[T]

None returns an absent Optional (the zero value).

func Null

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

Null returns an Optional that is present but explicitly null.

func Some

func Some[T any](v T) Optional[T]

Some returns an Optional holding v. Some of a zero value (e.g. Some(0) or Some("")) is still a value, not None.

func (Optional[T]) Get

func (o Optional[T]) Get() (T, bool)

Get returns the held value and true for Some; for None and Null it returns T's zero value and false.

func (Optional[T]) IsNull

func (o Optional[T]) IsNull() bool

IsNull reports whether the Optional is present and explicitly null.

func (Optional[T]) IsSet

func (o Optional[T]) IsSet() bool

IsSet reports whether the Optional is present, either as Null or as a value.

func (Optional[T]) IsSome

func (o Optional[T]) IsSome() bool

IsSome reports whether the Optional holds a value.

func (Optional[T]) IsZero

func (o Optional[T]) IsZero() bool

IsZero reports whether the Optional is None. encoding/json uses it to omit None fields tagged `json:",omitzero"`.

func (Optional[T]) MarshalJSON

func (o Optional[T]) MarshalJSON() ([]byte, error)

MarshalJSON encodes Some(v) as v and Null as null. None also encodes as null; tag the field `json:",omitzero"` to leave it out instead.

func (*Optional[T]) UnmarshalJSON

func (o *Optional[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a JSON null as Null and any other value as Some. A field missing from the input is never passed to UnmarshalJSON, so it keeps its zero value, None. On a decoding error the Optional is left unchanged.

Jump to

Keyboard shortcuts

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