go-util/container/option.go

41 lines
876 B
Go

package ucontainer
// Option can either hold a value, or nothing.
type Option[T any] struct {
value T
exists bool
}
// O creates a new option with the specified value.
func O[T any] (value T) Option[T] {
return Option[T] {
value: value,
exists: true,
}
}
// Void returns an option with no value.
func Void[T any] () Option[T] {
return Option[T] { }
}
// Exists returns if the value is currently set.
func (option Option[T]) Exists () bool {
return option.exists
}
// Value returns the value and true if the value exists. If not, it returns the
// zero value and false.
func (option Option[T]) Value () (T, bool) {
return option.value, option.exists
}
// Default returns the value if it exists, and the specified default value
// otherwise.
func (option Option[T]) Default(defaul T) T {
if value, ok := option.Value(); ok {
return value
}
return defaul
}