option

package
v0.19.0 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2026 License: MIT Imports: 2 Imported by: 0

README

option: nil-safe optional values

Represent values that may be absent. Options enforce checking before use—nil panics become compile-time errors.

An option is either ok (has a value) or not-ok (absent).

host := config.GetHost().Or("localhost")  // default if absent

See pkg.go.dev for complete API documentation. For the full discussion of nil safety, see Nil Safety in Go. For function naming patterns, see Naming Functions for Higher-Order Functions.

Quick Start

import "github.com/binaryphile/fluentfp/option"

// Create options
helloOption := option.Of("hello")       // ok
notOkString := option.NotOkString       // not-ok

// Extract with defaults
hello := helloOption.Or("fallback")
fallback := notOkString.Or("fallback")

// Check and extract
if hello, ok := helloOption.Get(); ok {
    // use hello
}

Types

Basic[T] holds an optional value—either "ok" (has value) or "not-ok" (absent).

Type aliases String, Int, Bool are shorthand for Basic[string], Basic[int], etc. See Type Aliases for the full list.

API Reference

Constructors
Function Signature Purpose Example
Of Of[T](T) Basic[T] Create ok option option.Of(user)
New New[T](T, bool) Basic[T] From value + ok flag option.New(val, ok)
NotOk NotOk[T]() Basic[T] Create not-ok option option.NotOk[User]()
IfNotZero IfNotZero[T comparable](T) Basic[T] Not-ok if zero value option.IfNotZero(count)
IfNotEmpty IfNotEmpty(string) String Not-ok if empty (string alias) option.IfNotEmpty(name)
IfNotNil IfNotNil[T](*T) Basic[T] Not-ok if nil option.IfNotNil(userPtr)
Getenv Getenv(string) String From env var option.Getenv("PORT")

Pseudo-options: Go APIs sometimes use *T (nil = absent) or zero values (empty string, 0, false, etc.) as pseudo-options. IfNotNil and IfNotZero convert these to formal options. IfNotEmpty is a readable alias for IfNotZero when the type is string.

Extraction Methods
Method Signature Purpose Example
.Get .Get() (T, bool) Comma-ok unwrap user, ok := userOption.Get()
.IsOk .IsOk() bool Check if ok if nameOption.IsOk()
.MustGet .MustGet() T Value or panic user = userOption.MustGet()
.Or .Or(T) T Value or default port = portOption.Or("8080")
.OrCall .OrCall(func() T) T Lazy default port = portOption.OrCall(findPort)
.OrZero .OrZero() T Value or zero name = nameOption.OrZero()
.OrEmpty .OrEmpty() T Alias for strings name = nameOption.OrEmpty()
.OrFalse .OrFalse() bool For option.Bool enabled = flagOption.OrFalse()
.ToOpt .ToOpt() *T Convert to pointer ptr = userOption.ToOpt()
Filtering Methods
Method Signature Purpose Example
.KeepOkIf .KeepOkIf(func(T) bool) Basic[T] Not-ok if false active = userOption.KeepOkIf(User.IsActive)
.ToNotOkIf .ToNotOkIf(func(T) bool) Basic[T] Not-ok if true valid = userOption.ToNotOkIf(User.IsExpired)
Mapping Methods
Method Signature Purpose Example
.Convert .Convert(func(T) T) Basic[T] Transform, same type normalized = userOption.Convert(User.Normalize)
.ToString .ToString(func(T) string) String Transform to string name = userOption.ToString(User.Name)
.ToInt .ToInt(func(T) int) Int Transform to int age = userOption.ToInt(User.Age)
Map Map[T,R](Basic[T], func(T)R) Basic[R] Transform to any type role = option.Map(userOption, User.Role)

Other To[Type] methods: ToAny, ToBool, ToByte, ToError, ToRune

Side Effects
Method Signature Purpose Example
.Call .Call(func(T)) Execute if ok userOption.Call(User.Save)
Lift Lift[T](func(T)) func(Basic[T]) Create named function accepting option saveUser := option.Lift(User.Save); saveUser(userOpt)
Type Aliases

Pre-defined types: String, Int, Bool, Error, Any, Byte, Rune

Pre-defined not-ok values: NotOkString, NotOkInt, NotOkBool, NotOkError, NotOkAny, NotOkByte, NotOkRune

When NOT to Use option

  • Go idiom (T, error) — Don't replace error returns with option
  • Performance-critical paths — Option adds a bool field; profile first
  • Simple nil checks — If if ptr != nil is clear, don't over-engineer
  • When error context matters — Option loses why something is absent

Patterns

Tri-State Boolean
type ScanResult struct {
    IsConnected option.Bool  // true, false, or unknown
}

connected := result.IsConnected.OrFalse()  // unknown → false
Nullable Database Fields
func (r Record) GetHost() option.String {
    return option.IfNotZero(r.NullableHost.String)
}
Advanced: Domain Option Types

For domain-specific behavior (conditional lifecycle management, dependency injection), see the advanced option example.

See Also

For typed failure values instead of absent, see either.

Documentation

Overview

Package option provides types and functions to work with optional values.

Index

Constants

This section is empty.

Variables

View Source
var (
	NotOkAny    = Basic[any]{}
	NotOkBool   = Basic[bool]{}
	NotOkByte   = Basic[byte]{}
	NotOkError  = Basic[error]{}
	NotOkInt    = Basic[int]{}
	NotOkRune   = Basic[rune]{}
	NotOkString = Basic[string]{}
)

Functions

func Lift added in v0.15.0

func Lift[T any](fn func(T)) func(Basic[T])

Lift transforms a function operating on T into one operating on Basic[T]. The lifted function executes only when the option is ok.

Types

type Any

type Any = Basic[any]

type Basic

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

Basic represents an optional value of type T.

func IfNotNil added in v0.10.0

func IfNotNil[T any](t *T) (_ Basic[T])

IfNotNil returns an ok option of *what t points at* provided that t is not nil, or not-ok otherwise. It converts a pointer-based pseudo-option (where nil means absent) into a formal option.

func IfNotZero added in v0.7.0

func IfNotZero[T comparable](t T) (_ Basic[T])

IfNotZero returns an ok option of t provided that t is not the zero value for T, or not-ok otherwise. Zero values include "" for strings, 0 for numbers, false for bools, etc.

func Map

func Map[T, R any](b Basic[T], fn func(T) R) (_ Basic[R])

func New

func New[T any](t T, ok bool) (_ Basic[T])

New returns an ok option of t provided that ok is true, or not-ok otherwise.

func NotOk

func NotOk[T any]() (_ Basic[T])

func Of

func Of[T any](t T) Basic[T]

Of returns an ok option of t, independent of t's value.

func (Basic[T]) Call

func (b Basic[T]) Call(fn func(T))

Call applies fn to the option's value provided that the option is ok.

func (Basic[T]) Convert added in v0.9.0

func (b Basic[T]) Convert(fn func(T) T) (_ Basic[T])

Convert returns the result of applying fn to the option's value provided that the option is ok, or not-ok otherwise.

func (Basic[T]) Get

func (b Basic[T]) Get() (_ T, _ bool)

Get returns the option's value and a boolean indicating the option's status. It unpacks the option's fields into Go's comma-ok idiom, making it useful in the usual Go conditional constructs. When used in this manner, myVal doesn't stick around in the namespace when you're done with it:

if myVal, ok := o.Get; ok {
  do some stuff
}

func (Basic[T]) IsOk

func (b Basic[T]) IsOk() bool

IsOk returns true if the option is ok.

func (Basic[T]) KeepOkIf

func (b Basic[T]) KeepOkIf(fn func(T) bool) (_ Basic[T])

KeepOkIf returns b provided that applying fn to an ok option's value returns true, or the original option otherwise. It is the filter operation. Since Go doesn't offer a convenient lambda syntax for constructing the negation of a function's output, there is a ToNotOkIf method as well.

func (Basic[T]) MarshalJSON added in v0.14.0

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

MarshalJSON serializes Option: Ok(v) → v, NotOk → null

func (Basic[T]) MustGet

func (b Basic[T]) MustGet() T

MustGet returns the option's value or panics if the option is not ok.

func (Basic[T]) Or

func (b Basic[T]) Or(t T) T

Or returns the option's value provided that the option is ok, otherwise t.

func (Basic[T]) OrCall

func (b Basic[T]) OrCall(fn func() T) (_ T)

OrCall returns the option's value provided that it is ok, otherwise the result of calling fn.

func (Basic[T]) OrEmpty

func (b Basic[T]) OrEmpty() (_ T)

OrEmpty returns the option's value provided that it is ok, otherwise the zero value for T. It is a more readable alias for OrZero when T is string.

func (Basic[T]) OrFalse

func (b Basic[T]) OrFalse() bool

OrFalse returns the option's value provided that it is ok, otherwise false. It is a readable alias for OrZero when the type is bool.

func (Basic[T]) OrZero

func (b Basic[T]) OrZero() (_ T)

OrZero returns the option's value provided that it is ok, otherwise the zero value for T. See OrEmpty and OrFalse for more readable aliases of OrZero when T is string or bool.

func (Basic[T]) ToAny

func (b Basic[T]) ToAny(fn func(T) any) (_ Basic[any])

ToAny returns an option of the result of applying fn to the option's value provided that the option is ok, or not-ok otherwise.

func (Basic[T]) ToBool

func (b Basic[T]) ToBool(fn func(T) bool) (_ Basic[bool])

ToBool returns an option of the result of applying fn to the option's value provided that the option is ok, or not-ok otherwise.

func (Basic[T]) ToByte

func (b Basic[T]) ToByte(fn func(T) byte) (_ Basic[byte])

ToByte returns an option of the result of applying fn to the option's value provided that the option is ok, or not-ok otherwise.

func (Basic[T]) ToError

func (b Basic[T]) ToError(fn func(T) error) (_ Basic[error])

ToError returns an option of the result of applying fn to the option's value provided that the option is ok, or not-ok otherwise.

func (Basic[T]) ToInt

func (b Basic[T]) ToInt(fn func(T) int) (_ Basic[int])

ToInt returns an option of the result of applying fn to the option's value provided that the option is ok, or not-ok otherwise.

func (Basic[T]) ToNotOkIf

func (b Basic[T]) ToNotOkIf(fn func(T) bool) (_ Basic[T])

ToNotOkIf returns a not-ok option provided that applying fn to an ok option's value returns true, or the original option otherwise. It is the filter operation with negation. Since Go doesn't offer a convenient lambda syntax for constructing the negation of a function's output, having negation built-in is both a convenience and keeps consuming code readable.

func (Basic[T]) ToOpt

func (b Basic[T]) ToOpt() (_ *T)

ToOpt returns a pointer-based pseudo-option of the pointed-at value provided that the option is ok, or not-ok otherwise. By convention, in consuming code, we suffix a pseudo-option's variable name with an "Opt" suffix to clarify the pointer's meaning and use, hence "ToOpt".

func (Basic[T]) ToRune

func (b Basic[T]) ToRune(fn func(T) rune) (_ Basic[rune])

ToRune returns an option of the result of applying fn to the option's value provided that the option is ok, or not-ok otherwise.

func (Basic[T]) ToString

func (b Basic[T]) ToString(fn func(T) string) (_ Basic[string])

ToString returns an option of the result of applying fn to the option's value provided that the option is ok, or not-ok otherwise.

func (*Basic[T]) UnmarshalJSON added in v0.14.0

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

UnmarshalJSON deserializes Option: null → NotOk, value → Ok(value)

type Bool

type Bool = Basic[bool]

type Byte

type Byte = Basic[byte]

type Error

type Error = Basic[error]

type Int

type Int = Basic[int]

type Rune

type Rune = Basic[rune]

type String

type String = Basic[string]

func Getenv

func Getenv(key string) String

func IfNotEmpty added in v0.12.0

func IfNotEmpty(s string) (_ String)

IfNotEmpty returns an ok option of s provided that s is not empty, or not-ok otherwise. It is a readable alias for IfNotZero when the type is string.

Jump to

Keyboard shortcuts

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