goutil/container/optional.go

32 lines
697 B
Go
Raw Normal View History

2024-09-10 14:47:20 -06:00
package ucontainer
2024-10-30 21:54:11 -06:00
// Optional can either hold a value, or nothing.
2024-09-10 14:47:20 -06:00
type Optional[T any] struct {
value T
exists bool
}
2024-10-30 21:54:11 -06:00
// O creates a new optional with the specified value.
func O[T any] (value T) Optional[T] {
return Optional[T] {
value: value,
exists: true,
}
2024-09-10 14:47:20 -06:00
}
2024-10-30 21:54:11 -06:00
// Void returns an optional with no value.
func Void[T any] () Optional[T] {
return Optional[T] { }
2024-09-10 14:47:20 -06:00
}
2024-10-30 21:54:11 -06:00
// Exists returns if the value is currently set.
func (optional Optional[T]) Exists () bool {
return optional.exists
2024-09-10 14:47:20 -06:00
}
2024-10-30 21:54:11 -06:00
// 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
2024-09-10 14:47:20 -06:00
}