2022-04-24 16:55:25 +00:00
|
|
|
package gonads
|
|
|
|
|
|
|
|
import "errors"
|
|
|
|
|
|
|
|
var (
|
|
|
|
ErrOptionIsNone = errors.New("gonads: Option[T] has no value")
|
|
|
|
)
|
|
|
|
|
|
|
|
// Option is a container that might contain a value.
|
|
|
|
type Option[T any] struct {
|
|
|
|
val *T
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsSome returns true if the Option has some value in it.
|
|
|
|
func (o Option[T]) IsSome() bool {
|
|
|
|
return o.val != nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsNone returns true if the Option has no value in it.
|
|
|
|
func (o Option[T]) IsNone() bool {
|
|
|
|
return !o.IsSome()
|
|
|
|
}
|
|
|
|
|
2022-04-24 17:21:57 +00:00
|
|
|
// Yank will pull a value out of an option, panicking if it doesn't exist.
|
|
|
|
func (o Option[T]) Yank() T {
|
|
|
|
if o.IsNone() {
|
|
|
|
panic("gonads: Yank on None Option")
|
|
|
|
}
|
|
|
|
|
|
|
|
return *o.val
|
|
|
|
}
|
|
|
|
|
2022-04-24 16:55:25 +00:00
|
|
|
// Take a value out of the option if it exists.
|
2022-04-24 17:21:57 +00:00
|
|
|
func (o Option[T]) Take() (T, error) {
|
2022-04-24 16:55:25 +00:00
|
|
|
if o.IsNone() {
|
2022-04-24 17:21:57 +00:00
|
|
|
var zero T
|
|
|
|
return zero, ErrOptionIsNone
|
2022-04-24 16:55:25 +00:00
|
|
|
}
|
|
|
|
|
2022-04-24 17:21:57 +00:00
|
|
|
return *o.val, nil
|
2022-04-24 16:55:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Set the value of the option to a given value.
|
|
|
|
func (o *Option[T]) Set(val T) {
|
|
|
|
o.val = &val
|
|
|
|
}
|
|
|
|
|
|
|
|
// Clear removes the value from an Option.
|
|
|
|
func (o *Option[T]) Clear() {
|
|
|
|
o.val = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewOption creates a new Option with the given type. All Options
|
|
|
|
// Start out as nil.
|
|
|
|
func NewOption[T any]() *Option[T] {
|
|
|
|
return &Option[T]{}
|
|
|
|
}
|