Skip to content

Instantly share code, notes, and snippets.

@J-Swift
Created June 3, 2025 17:37
Show Gist options
  • Save J-Swift/96cde097cc324de1f8e899ba30a16f9f to your computer and use it in GitHub Desktop.
Save J-Swift/96cde097cc324de1f8e899ba30a16f9f to your computer and use it in GitHub Desktop.
package util
import "errors"
// https://christine.website/blog/gonads-2022-04-24
type Option[T any] struct {
value *T
}
var ErrOptionIsNone = errors.New("gonads: Option[T] has no value")
func NewOption[T any]() *Option[T] {
return &Option[T]{}
}
func (o Option[T]) IsSome() bool {
return o.value != nil
}
func (o Option[T]) IsNone() bool {
return !o.IsSome()
}
func (o Option[T]) Take() (T, error) {
if o.IsNone() {
var zero T
return zero, ErrOptionIsNone
}
return *o.value, nil
}
func (o *Option[T]) Set(val T) {
o.value = &val
}
func (o *Option[T]) Clear() {
o.value = nil
}
func (o Option[T]) Yank() T {
if o.IsNone() {
panic("Yank on None Option")
}
return *o.value
}
package util
type Result[T any] struct {
value *T
err error
}
func ResultOk[T any](value T) Result[T] {
return Result[T]{value: &value, err: nil}
}
func ResultErr[T any](err error) Result[T] {
return Result[T]{value: nil, err: err}
}
func (res Result[T]) IsOk() bool {
return res.err == nil
}
func (res Result[T]) IsErr() bool {
return !res.IsOk()
}
func (res Result[T]) Value() T {
if !res.IsOk() {
panic("Yank on Err Result")
}
return *res.value
}
func (res Result[T]) Error() error {
if !res.IsErr() {
panic("Yank on OK Result")
}
return res.err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment