Improvements to Optional type

This commit is contained in:
Sasha Koshka 2024-10-30 23:54:11 -04:00
parent e6a94c487e
commit e5b35f3fcc

View File

@ -1,31 +1,31 @@
package ucontainer package ucontainer
// Optional is an optional value. // Optional can either hold a value, or nothing.
type Optional[T any] struct { type Optional[T any] struct {
value T value T
exists bool exists bool
} }
// Value returns the value and true if the value exists. If not, it returns the // O creates a new optional with the specified value.
// last set value and false. func O[T any] (value T) Optional[T] {
func (this *Optional[T]) Value () (T, bool) { return Optional[T] {
return this.value, this.exists value: value,
exists: true,
}
} }
// Set sets the value. // Void returns an optional with no value.
func (this *Optional[T]) Set (value T) { func Void[T any] () Optional[T] {
this.value = value return Optional[T] { }
this.exists = true
}
// Unset unsets the value.
func (this *Optional[T]) Unset () {
var zero T
this.value = zero
this.exists = false
} }
// Exists returns if the value is currently set. // Exists returns if the value is currently set.
func (this *Optional[T]) Exists () bool { func (optional Optional[T]) Exists () bool {
return this.exists 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
} }