go-util/container/optional.go

32 lines
697 B
Go

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