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 ¶
- Variables
- type Field
- func (f Field[T]) Get() (T, bool)
- func (f Field[T]) GetOr(fallback T) T
- func (f Field[T]) IsNull() bool
- func (f Field[T]) IsSet() bool
- func (f Field[T]) IsUnset() bool
- func (f Field[T]) IsZero() bool
- func (f Field[T]) MarshalJSON() ([]byte, error)
- func (f Field[T]) MarshalJSONTo(enc *jsontext.Encoder) error
- func (f Field[T]) Ptr() *T
- func (f *Field[T]) Scan(src any) error
- func (f Field[T]) State() State
- func (f Field[T]) String() string
- func (f *Field[T]) UnmarshalJSON(data []byte) error
- func (f *Field[T]) UnmarshalJSONFrom(dec *jsontext.Decoder) error
- func (f Field[T]) Value() (driver.Value, error)
- type State
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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 Of ¶
Of returns a Field set to v. Zero values such as 0, "", and false are set values, not null.
func (Field[T]) Get ¶
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]) IsZero ¶
IsZero reports whether f is unset. Encoding with `json:",omitzero"` uses it to leave unset fields out.
func (Field[T]) MarshalJSON ¶
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 ¶
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 ¶
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]) UnmarshalJSON ¶
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 ¶
UnmarshalJSONFrom is the streaming form of Field.UnmarshalJSON.