Skip to content

lukasngl/opt

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Go Reference

opt

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.

Install

go get github.com/lukasngl/opt

Requires Go 1.22+.

Usage

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")
}

Features

  • Concise: opt.T[V] and aliases like opt.Int keep declarations short.

  • Idiomatic: Get() returns (value, ok), matching Go patterns like map lookup and type assertions.

  • Compatible:

    • Pointers: Convert with FromPtr and ToPtr
    • Zero values: Convert with FromZeroable, honoring IsZero() methods
    • JSON: Implements json.Marshaler/Unmarshaler, with omitzero support (go1.24)
    • SQL: Implements driver.Valuer/sql.Scanner via sql.Null[V]
    • Iterators: All() returns iter.Seq[V] (Go 1.23+)
  • Functional utilities: Map, FlatMap, Filter, Or, OrElseGet, IfPresent — for when you have a function ready to pass. Otherwise if v, ok := o.Get(); ok is usually cleaner.

Prior Art

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() bool method for the omitzero tag.

About

optional type for go

Resources

License

Stars

Watchers

Forks

Packages

No packages published