https://github.com/metafates/opt
🫥 Yet another option type in Go, but done right
https://github.com/metafates/opt
Last synced: over 1 year ago
JSON representation
🫥 Yet another option type in Go, but done right
- Host: GitHub
- URL: https://github.com/metafates/opt
- Owner: metafates
- License: mit
- Created: 2025-02-24T15:35:26.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2025-03-17T09:17:14.000Z (over 1 year ago)
- Last Synced: 2025-03-17T10:29:18.978Z (over 1 year ago)
- Language: Go
- Homepage: https://pkg.go.dev/github.com/metafates/opt
- Size: 13.7 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Opt
[](http://godoc.org/github.com/metafates/opt)
Opt is a Go package for safe abstractions over optional values.
Inspired by the [Option type in Rust] and follows the same ideas and function signatures.
## Features
- Represent explicitly set values. For example: `{"b":2,"a":null}` and `{"b":2}` would be different states for `a` - explicit and implicit `None`.
- All the encoding and decoding functionality: json, gob, sql, text & binary.
- Adapters to construct options from pointers, zero values, and proto messages.
- No reflection.
## Install
```bash
go get github.com/metafates/opt
```
## Usage
See [example_test.go](./example_test.go) for more examples.
```go
package main
import (
"fmt"
"time"
"github.com/metafates/opt"
)
type User struct {
Birth opt.Opt[time.Time]
}
func (u User) Age() opt.Opt[int] {
return opt.Map(u.Birth, func(t time.Time) int {
return time.Now().Year() - t.Year()
})
}
func isAdult(age int) bool {
return age >= 18
}
func getUser(id int) opt.Opt[User] {
// ...
}
func main() {
if opt.AndThen(getUser(42), User.Age).IsSomeAnd(isAdult) {
fmt.Println("🍺!")
}
}
```
[Option type in Rust]: https://doc.rust-lang.org/std/option/enum.Option.html