Skip to content

Instantly share code, notes, and snippets.

@fitzy1321
Last active November 7, 2026 04:03
Show Gist options
  • Select an option

  • Save fitzy1321/fec0f99fb46a80dfda2d5a79aeddd867 to your computer and use it in GitHub Desktop.

Select an option

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 πŸ˜‰
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