Created
June 3, 2025 17:37
-
-
Save J-Swift/96cde097cc324de1f8e899ba30a16f9f to your computer and use it in GitHub Desktop.
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 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 | |
} |
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 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