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:
- JSON marshaling: implements json.Marshaler and json.Unmarshaler; Some(value) → value, None() → null
- SQL databases: implements driver.Valuer and sql.Scanner interfaces
- Iteration: works with Go 1.23+ iterators via Option.Iter method
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 ¶
- func Equal[T comparable](x, y Option[T]) bool
- func IsNone[T any](o Option[T]) bool
- func IsSome[T any](o Option[T]) bool
- func Unwrap[T any](o Option[T]) (T, bool)
- type Option
- func FromExistenceCheck[T any](v T, exists bool) Option[T]
- func FromIterator[T any](i iter.Seq[T]) Option[T]
- func FromPtr[T any](ptr *T) Option[T]
- func FromResult[T any](v T, err error) Option[T]
- func None[T any]() Option[T]
- func Or[T any](opts ...Option[T]) Option[T]
- func Some[T any](v T) Option[T]
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.
Types ¶
type Option ¶
type Option[T any] struct { // contains filtered or unexported fields }
Option represents optional values.
func FromExistenceCheck ¶
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
FromIterator returns an Option with the first value yielded from the iterator.
If the iterator yields no values, returns None.
func FromPtr ¶
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 ¶
FromResult returns an existing value if err == nil, otherwise returns a none.
func (Option[T]) Iter ¶
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 (Option[T]) Ptr ¶
func (o Option[T]) Ptr() *T
Ptr returns a pointer to the value.
If the option has no value, nil returned.