diff options
Diffstat (limited to 'option')
| -rw-r--r-- | option/option.go | 11 | ||||
| -rw-r--r-- | option/option_test.go | 6 |
2 files changed, 17 insertions, 0 deletions
diff --git a/option/option.go b/option/option.go index fc4cf3e..f89acf7 100644 --- a/option/option.go +++ b/option/option.go @@ -117,6 +117,8 @@ import ( "iter" ) +// TODO: with 1.27 support for type variables on methods, consider additional methods referencing U from Rust's Option type + // Option is a type that contains either one or no instances of T. type Option[T any] struct { // NOTE: `None()` must yield the zero value of this type. @@ -222,6 +224,15 @@ func (o Option[T]) Iter() iter.Seq[T] { } } +// Map applies the given function to the value contained in o, if there is one. +func (o Option[T]) Map[U any](mapping func(T) U) Option[U] { + if t, ok := o.Unpack(); ok { + return Some(mapping(t)) + } else { + return None[U]() + } +} + // Or returns the option itself if it contains a value, or otherwise returns "other". // // If you are passing the result of a function call, consider using OrElse() to avoid calling the function unless necessary. diff --git a/option/option_test.go b/option/option_test.go index 43d114e..20782a5 100644 --- a/option/option_test.go +++ b/option/option_test.go @@ -7,6 +7,7 @@ import ( "encoding/json" "fmt" "slices" + "strconv" "testing" "go.xyrillian.de/gg/assert" @@ -74,6 +75,11 @@ func TestIter(t *testing.T) { assert.Equal(t, slices.Collect(Some(42).Iter()), []int{42}) } +func TestMap(t *testing.T) { + assert.Equal(t, None[int]().Map(strconv.Itoa), None[string]()) + assert.Equal(t, Some(42).Map(strconv.Itoa), Some("42")) +} + func TestOr(t *testing.T) { none := None[int]() assert.Equal(t, none.Or(none), None[int]()) |
