https://github.com/yah01/ore
Option and Result types for GoLang
https://github.com/yah01/ore
golang option option-type optional result result-type rust
Last synced: 3 months ago
JSON representation
Option and Result types for GoLang
- Host: GitHub
- URL: https://github.com/yah01/ore
- Owner: yah01
- Created: 2022-03-17T18:27:02.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2022-03-17T18:44:34.000Z (almost 4 years ago)
- Last Synced: 2025-01-26T00:25:44.888Z (12 months ago)
- Topics: golang, option, option-type, optional, result, result-type, rust
- Language: Go
- Homepage:
- Size: 3.91 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Ore
Thanks to Go 1.18, Now we can implement Option and Result like Rust!
## Get Started
### Option
You can use Option to express "nullable", just like all of the gophers did with pointer:
```golang
type Map[K comparable, V any] struct {
inner map[K]V
}
func (mp *Map[K, V]) Get(key K) Option[V] {
v, ok := mp.inner[key]
if !ok {
return None[V]()
}
return Some(v)
}
func main() {
// init a Map
if v := mp.Get("hello"); v.Some() {
fmt.Println("we got value:", v.Value())
} else {
fmt.Println("failed to get value")
}
}
```
### Result
Result is "value or error":
```golang
func (mp *Map[K, V]) Get(key K) Result[V] {
v, ok := mp.inner[key]
if !ok {
return mp.err(errors.New("key not found"))
}
return Ok(v)
}
func main() {
// init a Map
if res := mp.Get("hello"); res.IsErr() {
fmt.Println("failed to get value of `hello`, err =", res.Err())
} else {
fmt.Println("value of `hello`:", res.Value())
}
}
```
Refer to [examples](examples/) for more.