Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/tizz98/results
Go library experimenting with result types, use at your own risk
https://github.com/tizz98/results
Last synced: 9 days ago
JSON representation
Go library experimenting with result types, use at your own risk
- Host: GitHub
- URL: https://github.com/tizz98/results
- Owner: tizz98
- License: mit
- Created: 2020-05-19T15:50:48.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2020-05-26T17:35:51.000Z (over 4 years ago)
- Last Synced: 2024-06-20T15:49:37.383Z (5 months ago)
- Language: Go
- Size: 80.1 KB
- Stars: 0
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Go Results
Similar `Result` structs like in Rust or other languages.
At a very high level, if Go had generics it would look like this:
```go
type Result struct {
value *T
err error
}
```In [Go 2](https://blog.tempus-ex.com/generics-in-go-how-they-work-and-how-to-play-with-them/), we might someday be able to write:
```go
type Result(type T) struct {
value *T
err error
}
```See [`example_test.go`](example_test.go) for usage.
## Example
```go
package mainimport (
"context"
"fmt"
"strconv""github.com/tizz98/results"
)func betterParser(v string) (result results.IntResult) {
val, err := strconv.Atoi(v)
if err != nil {
result.Err(err)
return
}result.Ok(val)
return
}func betterParser2(v string) (result results.IntResult) {
result.Set(strconv.Atoi(v))
return
}func main() {
result := betterParser("123").Unwrap()
fmt.Printf("Got: %d\n", result)result2 := betterParser2("456").Unwrap()
fmt.Printf("Got: %d\n", result2)// This will panic if you uncomment
// _ = betterParser2("foo").Unwrap()// Context usage
ctx := context.Background()
ctx = results.ContextWithInt(ctx, "foo", 4242)result3 := results.IntFromContext(ctx, "foo")
result4 := results.IntFromContext(ctx, "bar")fmt.Printf("%v: %d, %v: %d\n", result3.IsOk(), result3.Unwrap(), result4.IsOk(), result4.UnwrapOr(4567))
// Output: true: 4242, false: 4567
}
```## Struct example
```go
//go:generate go run github.com/tizz98/results/cmd -pkg foo -t *Bar -tup-default nil -result-name BarPtrResult
//go:generate go run github.com/tizz98/results/cmd -pkg foo -t Bar -tup-default Bar{} -result-name BarResult
package footype Bar struct {
Baz int
Field string
}
```