optional

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2025 License: MIT Imports: 5 Imported by: 0

README

status PkgGoDev

Installation

go get github.com/aereal/optional

Usage

See pkg.go.dev.

License

See LICENSE file.

Documentation

Overview

Package optional provides a generic optional type for Go, inspired by Scala's Option, and Haskell's Maybe types.

It offers a type-safe way to handle values that may or may not exist, eliminating the need for nil pointer checks and providing clearer semantics than (T, error) patterns or bare nil values.

The core type Option encapsulates an optional value of type T. Unlike bare pointers or any values, Option[T] makes the absence of a value explicit and type-safe, preventing runtime panics from nil dereferences.

Safety and Semantics

Option provides safer and more explicit semantics compared to traditional Go patterns:

  • No nil pointer dereferences: values are accessed through safe methods
  • Clear intention: the type system enforces handling of absent values

Integration

Option integrates seamlessly with Go's standard library:

Memory Efficiency

Option is designed with memory efficiency in mind:

  • Zero allocation for None values after initial creation
  • Single allocation for Some values
  • Compact representation: stores value and presence flag inline

Extensibility

The iterator-based design enables composition using standard iterator utilities.

This allows complex optional value manipulations using familiar Go iteration patterns without requiring Option-specific utility functions.

Example
package main

import (
	"fmt"

	"github.com/aereal/optional"
)

func main() {
	fmt.Print("Some: ")
	printOption(optional.Some("abc"))
	fmt.Print("None: ")
	printOption(optional.None[string]())
}

func printOption(o optional.Option[string]) {
	s, ok := optional.Unwrap(o)
	fmt.Printf("%q %v\n", s, ok)
}
Output:

Some: "abc" true
None: "" false

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Equal

func Equal[T comparable](x, y Option[T]) bool

Equal returns true if x and y are equal.

The Option's equality is defined by as below:

  • both options are none value, they are equal.
  • both options are some (existing) value and their underlying value are equal, they are equal.
  • otherwise, they are NOT equal.

func IsNone

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

IsNone predicates the option is none or not.

func IsSome

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

IsSome predicates the option is existing value or not.

func Unwrap

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

Unwrap unwraps the contained value from the option.

If the option is none, the false is returned.

Types

type Option

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

Option represents optional values.

func FromExistenceCheck

func FromExistenceCheck[T any](v T, exists bool) Option[T]

FromExistenceCheck returns an existing value if exists == true, otherwrise returns a none.

The existence check means (T, bool) tuple values, it is inspired by map type's special index expression.

func FromIterator added in v0.2.0

func FromIterator[T any](i iter.Seq[T]) Option[T]

FromIterator returns an Option with the first value yielded from the iterator.

If the iterator yields no values, returns None.

func FromPtr

func FromPtr[T any](ptr *T) Option[T]

FromPtr returns a some value if the pointer refers the existing value.

Example
package main

import (
	"fmt"

	"github.com/aereal/optional"
)

func main() {
	s := "abc"
	fmt.Print("presented pointer: ")
	printOption(optional.FromPtr(&s))
	fmt.Print("nil: ")
	printOption(optional.FromPtr((*string)(nil)))
}

func printOption(o optional.Option[string]) {
	s, ok := optional.Unwrap(o)
	fmt.Printf("%q %v\n", s, ok)
}
Output:

presented pointer: "abc" true
nil: "" false

func FromResult

func FromResult[T any](v T, err error) Option[T]

FromResult returns an existing value if err == nil, otherwise returns a none.

func None

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

None returns a none value.

func Or

func Or[T any](opts ...Option[T]) Option[T]

Or returns the first existing value or none if all of opts are none.

func Some

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

Some returns an existing value of type T.

func (Option[T]) Iter

func (o Option[T]) Iter() iter.Seq[T]

Iter iterates the option's value.

If the option has no value, nothing iterated.

Example
package main

import (
	"fmt"

	"github.com/aereal/optional"
)

func main() {
	fmt.Print("Some:")
	for s := range optional.Some("abc").Iter() {
		fmt.Printf(" %q\n", s)
	}
	fmt.Print("None:")
	for s := range optional.None[string]().Iter() {
		fmt.Printf(" %q\n", s)
	}
}
Output:

Some: "abc"
None:

func (Option[T]) MarshalJSON

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

func (Option[T]) Ptr

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

Ptr returns a pointer to the value.

If the option has no value, nil returned.

func (*Option[T]) Scan

func (o *Option[T]) Scan(src any) error

func (*Option[T]) UnmarshalJSON

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

func (Option[T]) Value

func (o Option[T]) Value() (driver.Value, error)

Jump to

Keyboard shortcuts

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