optional

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2026 License: Apache-2.0 Imports: 0 Imported by: 0

Documentation

Overview

Package optional provides a Maybe type representing an optional value.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Maybe

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

Maybe represents an optional value of type T. A Maybe is either Some (holding a value) or None (holding nothing).

func FlatMap

func FlatMap[T any, R any](m Maybe[T], fn func(T) Maybe[R]) Maybe[R]

FlatMap applies fn to the value inside m and returns the resulting Maybe. If m is empty, FlatMap returns an empty Maybe of type R.

func Map

func Map[T any, R any](m Maybe[T], fn func(T) R) Maybe[R]

Map applies fn to the value inside m and returns a new Maybe containing the result. If m is empty, Map returns an empty Maybe of type R.

Example
package main

import (
	"fmt"

	"github.com/mikehelmick/go-functional/optional"
)

func main() {
	length := func(s string) int { return len(s) }
	fmt.Println(optional.Map(optional.Some("hello"), length).MustGet())
	fmt.Println(optional.Map(optional.None[string](), length).IsEmpty())
}
Output:
5
true

func None

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

None returns an empty Maybe of type T.

Example
package main

import (
	"fmt"

	"github.com/mikehelmick/go-functional/optional"
)

func main() {
	m := optional.None[string]()
	fmt.Println(m.OrElse("default"))
}
Output:
default

func Some

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

Some returns a Maybe containing the given value.

Example
package main

import (
	"fmt"

	"github.com/mikehelmick/go-functional/optional"
)

func main() {
	m := optional.Some("hello")
	if v, ok := m.Get(); ok {
		fmt.Println(v)
	}
}
Output:
hello

func (Maybe[T]) Get

func (m Maybe[T]) Get() (T, bool)

Get returns the value and true if present, or the zero value of T and false if empty.

func (Maybe[T]) IsEmpty

func (m Maybe[T]) IsEmpty() bool

IsEmpty reports whether the Maybe holds no value.

func (Maybe[T]) IsPresent

func (m Maybe[T]) IsPresent() bool

IsPresent reports whether the Maybe holds a value.

func (Maybe[T]) MustGet

func (m Maybe[T]) MustGet() T

MustGet returns the value. It panics if the Maybe is empty.

func (Maybe[T]) OrElse

func (m Maybe[T]) OrElse(defaultVal T) T

OrElse returns the value if present, otherwise returns the provided default.

Jump to

Keyboard shortcuts

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