Skip to main content

optional

import "github.com/go-softwarelab/common/pkg/optional"

Variables

ValueNotPresent is the error returned or passed to iter.Seq2 when the value is not present.

var ValueNotPresent = errors.New(valueNotPresentErrorMessage)

type Value

Value represents an optional value.

type Value[V any] struct {
// contains filtered or unexported fields
}

Empty

func Empty[V any]() Value[V]

Empty returns an empty optional value.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
opt := optional.Empty[string]()
fmt.Println("Is empty:", opt.IsEmpty())
fmt.Println("Is present:", opt.IsPresent())

}

Output

Is empty: true
Is present: false

Map

func Map[E, R any](o Value[E], f func(E) R) Value[R]

Map is a function that maps the value of optional if it is present.

Example
package main

import (
"fmt"
"strings"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
// Map a present value
opt := optional.Of("hello")

// Map to uppercase
upperOpt := optional.Map(opt, strings.ToUpper)
fmt.Println("Mapped value:", upperOpt.MustGet())

// Map with more complex function
lenOpt := optional.Map(opt, func(s string) int {
return len(s)
})
fmt.Println("String length:", lenOpt.MustGet())

}

Output

Mapped value: HELLO
String length: 5
Example (Chain)
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
// Chaining multiple Map operations
opt := optional.Of(42)

msg := optional.Map(opt, func(n int) string {
return fmt.Sprintf("Number: %d", n)
})

result := optional.Map(msg, func(s string) []byte {
return []byte(s)
})

// Check if result is present
if result.IsPresent() {
fmt.Printf("Result type: %T\n", result.MustGet())
fmt.Printf("Result length: %d\n", len(result.MustGet()))
}

}

Output

Result type: []uint8
Result length: 10
Example (Empty)
package main

import (
"fmt"
"strings"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
// Map an empty optional
emptyOpt := optional.Empty[string]()

// Map function won't be called for empty optionals
mapped := optional.Map(emptyOpt, strings.ToUpper)

fmt.Println("Is mapped empty:", mapped.IsEmpty())
fmt.Println("Is mapped present:", mapped.IsPresent())

}

Output

Is mapped empty: true
Is mapped present: false

None

func None[V any]() Value[V]

None returns an empty optional value. alias: Empty

Of

func Of[E any](v E) Value[E]

Of returns an optional with the given value. If the value is a pointer, and it's nil, it returns an empty optional. Otherwise, it returns non-empty optional with the given value.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
// With a value
opt := optional.Of("hello")
fmt.Println("Value:", opt.MustGet())
fmt.Println("Is empty:", opt.IsEmpty())

// With a nil pointer
var ptr *string = nil
optPtr := optional.Of(ptr)
fmt.Println("Nil pointer optional is empty:", optPtr.IsEmpty())

}

Output

Value: hello
Is empty: false
Nil pointer optional is empty: true

OfPtr

func OfPtr[E any](v *E) Value[E]

OfPtr returns an optional with the value from pointer. If the pointer is nil, it returns an empty optional. Otherwise, it returns non-empty optional with the value pointed to by the pointer.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
// With a value pointer
value := "hello"
opt := optional.OfPtr(&value)
fmt.Println("Value:", opt.MustGet())

// With a nil pointer
var nilPtr *string
optNil := optional.OfPtr(nilPtr)
fmt.Println("Is empty:", optNil.IsEmpty())

}

Output

Value: hello
Is empty: true

OfValue

func OfValue[E comparable](v E) Value[E]

OfValue returns an optional for the given value. If value is zero value, it returns an empty optional. Otherwise, it returns non-empty optional with the given value.

If zero value is valid existing value for you, for example when the value is int, then prefer Of() instead.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
// Non-zero value
opt := optional.OfValue(42)
fmt.Println("Value present:", opt.IsPresent())
fmt.Println("Value:", opt.MustGet())

// Zero value
optZero := optional.OfValue(0)
fmt.Println("Zero value present:", optZero.IsPresent())

}

Output

Value present: true
Value: 42
Zero value present: false

Some

func Some[V any](v V) Value[V]

Some returns an optional with the given value. It doesn't make any checks on value - it was caller decision to understand this value as present.

Value[V].IfNotPresent

func (o Value[V]) IfNotPresent(fn func())

IfNotPresent executes the function if the value is not present.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
opt := optional.Of("hello")
empty := optional.Empty[string]()

opt.IfNotPresent(func() {
fmt.Println("This won't be printed")
})

empty.IfNotPresent(func() {
fmt.Println("This executes when empty")
})

}

Output

This executes when empty

Value[V].IfPresent

func (o Value[V]) IfPresent(fn func(V))

IfPresent executes the function if the value is present.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
opt := optional.Of("hello")
empty := optional.Empty[string]()

opt.IfPresent(func(value string) {
fmt.Println("Value is present:", value)
})

empty.IfPresent(func(value string) {
fmt.Println("This won't be printed")
})

}

Output

Value is present: hello

Value[V].IsEmpty

func (o Value[V]) IsEmpty() bool

IsEmpty returns true if the value is not present.

Value[V].IsNotEmpty

func (o Value[V]) IsNotEmpty() bool

IsNotEmpty returns true if the value is present.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
opt := optional.Of("hello")
empty := optional.Empty[string]()

fmt.Println("First is not empty:", opt.IsNotEmpty())
fmt.Println("Second is not empty:", empty.IsNotEmpty())

}

Output

First is not empty: true
Second is not empty: false

Value[V].IsPresent

func (o Value[V]) IsPresent() bool

IsPresent returns true if the value is present.

Value[V].MustGet

func (o Value[V]) MustGet() V

MustGet returns the value if present, otherwise panics.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
opt := optional.Of("hello")
fmt.Println("Value:", opt.MustGet())

// Note: Using MustGet on empty optional would panic
// empty := optional.Empty[string]()
// empty.MustGet() // would panic with "value is not present"

}

Output

Value: hello

Value[V].MustGetf

func (o Value[V]) MustGetf(msg string, args ...any) V

MustGetf returns the value if present, otherwise panics with a custom message.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
opt := optional.Of("hello")
fmt.Println("Value:", opt.MustGetf("Custom error: %s", "not found"))

// Note: Using MustGetf on empty optional would panic with custom message
// empty := optional.Empty[string]()
// empty.MustGetf("Custom error: %s", "not found") // would panic with "Custom error: not found"

}

Output

Value: hello

Value[V].Or

func (o Value[V]) Or(other Value[V]) Value[V]

Or returns this optional if present, otherwise returns the other optional.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
opt1 := optional.Of("first")
opt2 := optional.Of("second")
empty := optional.Empty[string]()

// Present optional takes precedence
fmt.Println("First or second:", opt1.Or(opt2).MustGet())
fmt.Println("Empty or second:", empty.Or(opt2).MustGet())

}

Output

First or second: first
Empty or second: second

Value[V].OrElse

func (o Value[V]) OrElse(defaultValue V) V

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

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
opt := optional.Of("hello")
empty := optional.Empty[string]()

fmt.Println("Present value:", opt.OrElse("default"))
fmt.Println("Empty value:", empty.OrElse("default"))

}

Output

Present value: hello
Empty value: default

Value[V].OrElseGet

func (o Value[V]) OrElseGet(defaultValue func() V) V

OrElseGet returns the value if present, otherwise returns the default value from the function.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
opt := optional.Of("hello")
empty := optional.Empty[string]()

counter := 0
getDefault := func() string {
counter++
return fmt.Sprintf("default-%d", counter)
}

fmt.Println("Present value:", opt.OrElseGet(getDefault))
fmt.Println("Empty value:", empty.OrElseGet(getDefault))
fmt.Println("Empty value again:", empty.OrElseGet(getDefault))

}

Output

Present value: hello
Empty value: default-1
Empty value again: default-2

Value[V].OrError

func (o Value[V]) OrError(err error) (V, error)

OrError returns the value if present, otherwise returns the error.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
opt := optional.Of(42)
empty := optional.Empty[int]()

val1, err1 := opt.OrError(fmt.Errorf("not found"))
fmt.Println("Value:", val1)
fmt.Println("Error:", err1)

val2, err2 := empty.OrError(fmt.Errorf("not found"))
fmt.Println("Empty value:", val2)
fmt.Println("Empty error:", err2 != nil)

}

Output

Value: 42
Error: <nil>
Empty value: 0
Empty error: true

Value[V].OrErrorGet

func (o Value[V]) OrErrorGet(err func() error) (V, error)

OrErrorGet returns the value if present, otherwise returns the error from the function.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
opt := optional.Of(42)
empty := optional.Empty[int]()

errCounter := 0
getError := func() error {
errCounter++
return fmt.Errorf("not found-%d", errCounter)
}

val1, err1 := opt.OrErrorGet(getError)
fmt.Println("Value:", val1)
fmt.Println("Error:", err1)

val2, err2 := empty.OrErrorGet(getError)
fmt.Println("Empty value:", val2)
fmt.Println("Empty error:", err2)

}

Output

Value: 42
Error: <nil>
Empty value: 0
Empty error: not found-1

Value[V].OrZeroValue

func (o Value[V]) OrZeroValue() V

OrZeroValue returns the value if present, otherwise returns the zero value of the type.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
opt := optional.Of(42)
empty := optional.Empty[int]()

fmt.Println("Present value:", opt.OrZeroValue())
fmt.Println("Empty value:", empty.OrZeroValue())

}

Output

Present value: 42
Empty value: 0

Value[V].Seq

func (o Value[V]) Seq() iter.Seq[V]

Seq returns the sequence with yelded value if present, otherwise returns an empty sequence.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
"github.com/go-softwarelab/common/pkg/seq"
)

func main() {
opt := optional.Of("hello")

var values []string
seq.ForEach(opt.Seq(), func(value string) {
values = append(values, value)
})

fmt.Println("Values:", values)

empty := optional.Empty[string]()
var emptyValues []string
seq.ForEach(empty.Seq(), func(value string) {
emptyValues = append(emptyValues, value)
})

fmt.Println("Empty values length:", len(emptyValues))

}

Output

Values: [hello]
Empty values length: 0

Value[V].Seq2

func (o Value[V]) Seq2() iter.Seq2[V, error]

Seq2 returns the iter.Seq2[V, error] with yelded value if present, otherwise yields an error. Useful with usage of seqerr package.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
"github.com/go-softwarelab/common/pkg/seqerr"
)

func main() {
opt := optional.Of("hello")
empty := optional.Empty[string]()

err := seqerr.ForEach(opt.Seq2(), func(value string) {
fmt.Printf("Value: %s\n", value)
})
if err != nil {
panic(err)
}

// With empty value
err = seqerr.ForEach(empty.Seq2(), func(value string) {
fmt.Printf("Unexpected value: %s\n", value)
})
if err != nil {
fmt.Printf("Expected error: %v\n", err)
}
}

Output

Value: hello
Expected error: value is not present

Value[V].ShouldGet

func (o Value[V]) ShouldGet() (V, error)

ShouldGet returns the value if present, otherwise returns the error ValueNotPresent.

Example
package main

import (
"fmt"

"github.com/go-softwarelab/common/pkg/optional"
)

func main() {
opt := optional.Of(42)
empty := optional.Empty[int]()

val1, err1 := opt.ShouldGet()
fmt.Println("Value:", val1)
fmt.Println("Error:", err1)

val2, err2 := empty.ShouldGet()
fmt.Println("Empty value:", val2)
fmt.Println("Empty error:", err2)

}

Output

Value: 42
Error: <nil>
Empty value: 0
Empty error: value is not present