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 Some ¶
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 ¶
Get returns the held value and true for Some; for None and Null it returns T's zero value and false.
func (Optional[T]) IsSet ¶
IsSet reports whether the Optional is present, either as Null or as a value.
func (Optional[T]) IsZero ¶
IsZero reports whether the Optional is None. encoding/json uses it to omit None fields tagged `json:",omitzero"`.
func (Optional[T]) MarshalJSON ¶
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 ¶
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.