Skip to content

Support user-friendly, type-safe optionals in Go.

License

Notifications You must be signed in to change notification settings

BooleanCat/option

Repository files navigation

Optional Values in Go

GitHub release (with filter) Actions Status Go Reference Go Report Card codecov

Support user-friendly, type-safe optionals in Go.

value = option.Some(4)
no_value = option.None[int]()

Read the docs.

Usage

This package adds a single type, the Option. Option's are instantiated as one of two variants. Some denotes the presence of a value and None denotes the absence.

Historically pointers have been used to denote optional values, this package removes the risk of null pointer exceptions by leveraging generics to implement type-safe optional values.

Options can be tested for the presence of a value:

two = option.Some(2)
if two.IsSome() {
    ...
}

Values can be extracted along with a boolean test for their presence:

two = option.Some(2)
if value, ok := two.Value(); ok {
    ...
}

Optionals that you're sure have a value can be "unwrapped":

two := option.Some(2)
two.Unwrap()  // returns 2

Accessing a value on a None variant will cause a runtime panic.

none := option.None[int]()
none.Unwrap()  // panics

Ergonomics

Use of a package like this may be pervasive if you really commit to it. This package was inspired by Rust's options implemenation. It might be worth considering dropping the repetative option. preceding the variants. Since importing names into the global namespace is to be avoided, the following import pattern may work for you:

import (
    "fmt"

    "github.com/BooleanCat/option"
)

var (
    Some = option.Some
    None = option.None
)

func main() {
    two := Some(2)
    fmt.Println(two)
}

About

Support user-friendly, type-safe optionals in Go.

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks