optional

package
v0.19.19 Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2025 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package optional provides a way to represent optional values.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Compare

func Compare[T cmp.Ordered](a, b Optional[T]) int

Compare returns an integer comparing two optional values.

An absent value is less than a present value.

func Equal

func Equal[T comparable](a, b Optional[T]) bool

Equal returns true if two optional values are equal.

Two absent values are considered equal.

Types

type Optional

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

Optional represents an optional value of type T.

func As

func As[T any, X any](
	x Optional[X],
) Optional[T]

As applies a type assertion to v. It returns an empty optional value if the type assertion fails.

func AtIndex

func AtIndex[E any, S ~[]E](s S, i int) Optional[E]

AtIndex returns the element at index i in s, or None if i is out of bounds.

func First

func First[E any, S ~[]E](s S) Optional[E]

First returns the first element in s, or None if s is empty.

func Key

func Key[K comparable, V any, M ~map[K]V](m M, k K) Optional[V]

Key returns the value associated with key k in map m, or None if k is not present in m.

func Last

func Last[E any, S ~[]E](s S) Optional[E]

Last returns the last element in s, or None if s is empty.

func None

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

None returns an Optional[T] that does not contain a value.

func Some

func Some[T any](v T) Optional[T]

Some returns an Optional[T] that contains the given value.

func Transform

func Transform[T, X any](
	x Optional[X],
	fn func(X) T,
) Optional[T]

Transform applies a transformation to v, returning a new optional value that contains the result of the function.

If v's value is not present, the returned optional value will also not contain a value.

func TryTransform

func TryTransform[T, X any](
	x Optional[X],
	fn func(X) (T, bool),
) Optional[T]

TryTransform applies a transformation to v, returning a new optional value that contains the result of the function.

If v's value is not present, the returned optional value will also not contain a value.

func (Optional[T]) Format

func (o Optional[T]) Format(state fmt.State, verb rune)

Format implements fmt.Formatter.

func (Optional[T]) Get

func (o Optional[T]) Get() T

Get returns the optional value, or panics if it is not present.

func (Optional[T]) IsPresent

func (o Optional[T]) IsPresent() bool

IsPresent returns true if the optional value is present.

func (Optional[T]) TryGet

func (o Optional[T]) TryGet() (T, bool)

TryGet returns the optional value and a boolean indicating whether it is present.

Jump to

Keyboard shortcuts

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