option

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package option provides a generic Option[T] type that represents either a present, non-nil value or its absence — the replacement for a nil-pointer check. nil and absent are the same concept: a Some can never hold nil.

Map, FlatMap, and Then use Go 1.27 generic methods, enabling clean method-chaining across type boundaries without nested free functions.

var p *User
name := option.From(p).
    Map(func(u *User) string { return u.Name }).
    OrElse("")

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Contains added in v0.9.0

func Contains[T comparable](o Option[T], target T) bool

Contains reports whether o is present and holds a value equal to target.

func Somes

func Somes[T any](options []Option[T]) []T

Somes returns every present value, dropping absences. Unlike Sequence, this never fails: an Option slice with no present values returns an empty slice.

Types

type Option

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

Option holds either a present, non-nil value of type T or nothing. The two are mutually exclusive by construction (there is no way to construct an Option with ok true and a nil val), so ok alone is the discriminant — there's no separate tag to keep in sync. Use Some, None, or From to construct; never use the zero value directly (though the zero value does happen to equal None[T]()).

func Flatten added in v0.9.0

func Flatten[T any](o Option[Option[T]]) Option[T]

Flatten collapses a nested Option[Option[T]] into a single Option[T].

func From

func From[T any](val T) Option[T]

From converts a possibly-nil value into an Option: nil becomes None, anything else becomes Some.

var p *User
option.From(p) // None

func FromMap added in v0.8.0

func FromMap[K comparable, V any](m map[K]V, key K) Option[V]

FromMap returns Some(val) if key is present in m and its value is non-nil; otherwise it returns None.

func FromNonZero added in v0.11.0

func FromNonZero[T comparable](val T) Option[T]

FromNonZero returns Some(val) if val is non-zero (val != zero); otherwise it returns None.

func FromOk added in v0.8.0

func FromOk[T any](val T, ok bool) Option[T]

FromOk converts a Go-idiomatic (val, ok) pair (e.g. map lookup, channel receive, type assertion) into an Option: returns Some(val) if ok is true and val is non-nil; otherwise returns None.

func FromResult added in v0.9.0

func FromResult[T any](r result.Result[T]) Option[T]

FromResult converts a result.Result[T] into an Option[T]: an error becomes None, and a success value becomes Some(val).

func FromSlice added in v0.8.0

func FromSlice[T any](slice []T, idx int) Option[T]

FromSlice returns Some(slice[idx]) if idx is within bounds [0, len(slice)); otherwise it returns None.

func None

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

None represents absence.

func Sequence

func Sequence[T any](options []Option[T]) Option[[]T]

Sequence turns a slice of Options into an Option of a slice, fail-fast on the first absence encountered — Haskell's sequence/traverse for []Option.

func Some

func Some[T any](val T) Option[T]

Some wraps a present value. Panics if val is nil (a nil pointer, interface, map, slice, chan, or func) — nil and absent are the same concept for Option, so a Some holding nil would be a contradiction. Use None for absence, or From if val's nilness isn't already known to be checked.

func Void added in v0.14.0

func Void() Option[unit.Unit]

Void returns a present Option carrying no value.

func Zip2

func Zip2[A, B, U any](oa Option[A], ob Option[B], fn func(A, B) U) Option[U]

Zip2 combines two independent Options into one via fn. Both must be present; the first absence (oa, then ob) short-circuits.

func Zip3

func Zip3[A, B, C, U any](oa Option[A], ob Option[B], oc Option[C], fn func(A, B, C) U) Option[U]

Zip3 combines three independent Options into one via fn. All three must be present; the first absence (oa, then ob, then oc) short-circuits.

func (Option[T]) Expect

func (o Option[T]) Expect(msg string) T

Expect returns the value or panics with msg if absent — the friendly alternative to MustGet for init/construction code, where a bare "called on None" panic isn't enough context to diagnose from.

func (Option[T]) Filter

func (o Option[T]) Filter(fn func(T) bool) Option[T]

Filter keeps a present value only if fn reports true for it; otherwise (or if already absent) the result is None.

func (Option[T]) FlatMap

func (o Option[T]) FlatMap[U any](fn func(T) Option[U]) Option[U]

FlatMap chains an Option-returning operation. Absence short-circuits: a None Option never calls fn.

func (Option[T]) Fold

func (o Option[T]) Fold[U any](onSome func(T) U, onNone func() U) U

Fold collapses the Option into a single value of type U by handling both branches — onSome for presence, onNone for absence. Equivalent to Haskell's maybe, and shorter than the equivalent Map(onSome).OrElseGet(onNone) two-step.

func (Option[T]) IsNone

func (o Option[T]) IsNone() bool

IsNone reports whether the Option is empty.

func (Option[T]) IsSome

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

IsSome reports whether the Option holds a value.

func (Option[T]) Map

func (o Option[T]) Map[U any](fn func(T) U) Option[U]

Map transforms the value into a different type. Absence propagates unchanged. Panics if fn returns nil — the same invariant Some enforces.

func (Option[T]) Map0 added in v0.14.0

func (o Option[T]) Map0[U any](fn func() U) Option[U]

Map0 maps the Option to a new type by calling fn with no arguments, ignoring the current value. Absence propagates unchanged.

func (Option[T]) MarshalJSON

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

MarshalJSON writes the value itself when present, or null when absent — safe precisely because Some can never hold nil, so there's no "present but nil" case that null could be confused with.

func (Option[T]) MustGet

func (o Option[T]) MustGet() T

MustGet returns the value or panics if absent. Intended for tests and initialisation code only.

func (Option[T]) Or added in v0.9.0

func (o Option[T]) Or(fallback Option[T]) Option[T]

Or returns o if it holds a value; otherwise it returns fallback Option.

func (Option[T]) OrElse

func (o Option[T]) OrElse(fallback T) T

OrElse returns the value, or fallback if absent. fallback is evaluated by the caller before this is called, regardless of branch — Go has no way to defer argument evaluation — the same gotcha as Rust's unwrap_or and Java's Optional.orElse. Use OrElseGet if fallback is expensive to compute.

func (Option[T]) OrElseGet

func (o Option[T]) OrElseGet(fn func() T) T

OrElseGet calls fn to produce a fallback value if absent.

func (Option[T]) Tap

func (o Option[T]) Tap(fn func(T)) Option[T]

Tap calls fn on the value for side effects (e.g. metrics, tracing) and passes the Option through unchanged.

func (Option[T]) Then

func (o Option[T]) Then[U any](fn func(T) (U, bool)) Option[U]

Then chains a Go-idiomatic (U, bool)-returning function.

func (Option[T]) ToPtr

func (o Option[T]) ToPtr() *T

ToPtr returns a pointer to the value, or nil if absent.

func (Option[T]) ToResult added in v0.9.0

func (o Option[T]) ToResult(err error) result.Result[T]

ToResult converts the Option into a result.Result[T], returning result.OK(val) if present, or result.Err(err) if absent.

func (Option[T]) ToResultGet added in v0.9.0

func (o Option[T]) ToResultGet(fn func() error) result.Result[T]

ToResultGet converts the Option into a result.Result[T], returning result.OK(val) if present, or result.Err(fn()) if absent.

func (Option[T]) ToSlice added in v0.9.0

func (o Option[T]) ToSlice() []T

ToSlice returns a single-element slice containing the value if present, or nil if absent.

func (*Option[T]) UnmarshalJSON

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

UnmarshalJSON reads null as None, and anything else as Some of the decoded value. Returns an error (not a panic — this is untrusted input, unlike Some) if the JSON decodes to a nil value despite not being null.

func (Option[T]) Unwrap

func (o Option[T]) Unwrap() (T, bool)

Unwrap returns the underlying (value, present) pair, matching Go's standard comma-ok convention for direct use in callers.

Jump to

Keyboard shortcuts

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