Last active
June 27, 2026 04:46
-
-
Save fitzy1321/fec0f99fb46a80dfda2d5a79aeddd867 to your computer and use it in GitHub Desktop.
Golang Result type. Use this in your channels to pass values and errors between goroutine π
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package result | |
| import ( | |
| "errors" | |
| "fmt" | |
| "sync" | |
| ) | |
| type Result[T any] struct { | |
| Value T | |
| err error | |
| } | |
| func Ok[T any](val T) Result[T] { | |
| return Result[T]{val, nil} | |
| } | |
| func Err[T any](err error) Result[T] { | |
| var t T | |
| return Result[T]{t, err} | |
| } | |
| func ErrFromStr[T any](errMsg string) Result[T] { | |
| var t T | |
| return Result[T]{t, errors.New(errMsg)} | |
| } | |
| func (r Result[T]) IsOk() bool { | |
| return r.err == nil | |
| } | |
| func (r Result[T]) IsErr() bool { | |
| return r.err != nil | |
| } | |
| func (r *Result[T]) GetError() error { | |
| return r.err | |
| } | |
| // Error Interface | |
| func (r *Result[T]) Error() string { | |
| return r.err.Error() | |
| } | |
| func Equal[T comparable](r, other Result[T]) bool { | |
| if r.IsOk() && other.IsOk() { | |
| return r.Value == other.Value | |
| } | |
| if r.IsErr() && other.IsErr() { | |
| return r.Error() == other.Error() | |
| } | |
| return false | |
| } | |
| func ExampleWithChannel() { | |
| type payload struct { | |
| Meaning int | |
| } | |
| ch := make(chan Result[payload], 2) | |
| go func() { | |
| ch <- Ok(payload{42}) | |
| }() | |
| go func() { | |
| ch <- Err[payload](errors.New("go func error happened ...")) | |
| }() | |
| for range 2 { | |
| result := <-ch | |
| if result.IsErr() { | |
| fmt.Fprintf(os.Stderr, "Error from goroutine: %+v\n", result) | |
| } | |
| if result.IsOk() { | |
| fmt.Printf("From my goroutine: %+v\n", result) | |
| } | |
| } | |
| close(ch) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment