Last active
November 7, 2026 04:03
-
-
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" | |
| ) | |
| type Result[V any] struct { | |
| Value V | |
| Err error | |
| } | |
| func Ok[T any](val T) Result[T] { | |
| return Result[T]{Value: val} | |
| } | |
| func Fail[T any](err error) Result[T] { | |
| return Result[T]{Err: err} | |
| } | |
| func ErrFromStr[T any](errMsg string) Result[T] { | |
| return Result[T]{Err: errors.New(errMsg)} | |
| } | |
| func Wrap[T any](v T, err error) Result[T] { | |
| return Result[T]{v, err} | |
| } | |
| 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.Err == other.Err | |
| } | |
| return false | |
| } | |
| func (r *Result[V]) IsOk() bool { | |
| return r.Err == nil | |
| } | |
| func (r *Result[V]) IsErr() bool { | |
| return r.Err != nil | |
| } | |
| // Error Interface | |
| func (r *Result[V]) Error() string { | |
| return r.Err.Error() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment