https://github.com/BooleanCat/option
Support user-friendly, type-safe optionals in Go.
https://github.com/BooleanCat/option
Last synced: 11 months ago
JSON representation
Support user-friendly, type-safe optionals in Go.
- Host: GitHub
- URL: https://github.com/BooleanCat/option
- Owner: BooleanCat
- License: mit
- Created: 2024-05-16T13:44:05.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2024-05-16T14:39:26.000Z (almost 2 years ago)
- Last Synced: 2024-11-12T15:30:47.685Z (over 1 year ago)
- Language: Go
- Homepage:
- Size: 11.7 KB
- Stars: 56
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
- Security: SECURITY.md
Awesome Lists containing this project
README
# Optional Values in Go
[](https://github.com/BooleanCat/option/releases) [](https://github.com/BooleanCat/option/actions) [](https://pkg.go.dev/github.com/BooleanCat/option) [](https://goreportcard.com/report/github.com/BooleanCat/option) [](https://codecov.io/gh/BooleanCat/option)
Support user-friendly, type-safe optionals in Go.
```go
value = option.Some(4)
no_value = option.None[int]()
```
_[Read the docs.](https://pkg.go.dev/github.com/BooleanCat/option)_
## 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:
```go
two = option.Some(2)
if two.IsSome() {
...
}
```
Values can be extracted along with a boolean test for their presence:
```go
two = option.Some(2)
if value, ok := two.Value(); ok {
...
}
```
Optionals that you're sure have a value can be "unwrapped":
```go
two := option.Some(2)
two.Unwrap() // returns 2
```
Accessing a value on a `None` variant will cause a runtime panic.
```go
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:
```go
import (
"fmt"
"github.com/BooleanCat/option"
)
var (
Some = option.Some
None = option.None
)
func main() {
two := Some(2)
fmt.Println(two)
}
```