Optionality is often implicitly represented by overloading the semantics of
pointers or zeroness.
This package exports the opt.T type and aliases for built-in types,
to explicitly represent optional values.
go get github.com/lukasngl/optRequires Go 1.22+.
type Query struct {
OrderBy opt.T[OrderBy] `json:"orderBy,omitzero"`
Limit opt.Int `json:"limit,omitzero"`
Offset opt.Int `json:"offset,omitzero"`
}value, ok := optional.Get()
if !ok {
return fmt.Errorf("not present")
}-
Concise:
opt.T[V]and aliases likeopt.Intkeep declarations short. -
Idiomatic:
Get()returns(value, ok), matching Go patterns like map lookup and type assertions. -
Compatible:
- Pointers: Convert with
FromPtrandToPtr - Zero values: Convert with
FromZeroable, honoringIsZero()methods - JSON: Implements
json.Marshaler/Unmarshaler, withomitzerosupport (go1.24) - SQL: Implements
driver.Valuer/sql.Scannerviasql.Null[V] - Iterators:
All()returnsiter.Seq[V](Go 1.23+)
- Pointers: Convert with
-
Functional utilities:
Map,FlatMap,Filter,Or,OrElseGet,IfPresent— for when you have a function ready to pass. Otherwiseif v, ok := o.Get(); okis usually cleaner.
There are loads of other optional type packages, but all of them had at least one of the following deal-breakers:
- Really long type names — the TypeScript folks just suffix a question mark, so why should we suffer?
- A slice-based approach — forces the value onto the heap and stores length and capacity, leading to unnecessary overhead.
- No
IsZero() boolmethod for theomitzerotag.