diff options
| author | Stefan Majewsky <majewsky@gmx.net> | 2026-10-18 19:33:33 +0200 |
|---|---|---|
| committer | Stefan Majewsky <majewsky@gmx.net> | 2026-10-18 19:33:33 +0200 |
| commit | 29b3b63b404c6a2cec28ff5eb067efe0b054a37f (patch) | |
| tree | 8086cc0a5bcf0bffb1458c19d7fae45f3b50a1df /option/option.go | |
| parent | 793e1705b4c34405f24d0f95ab532b68e8db673a (diff) | |
| download | go-gg-29b3b63b404c6a2cec28ff5eb067efe0b054a37f.tar.gz | |
add option.Option.Map()
Diffstat (limited to 'option/option.go')
| -rw-r--r-- | option/option.go | 11 |
1 files changed, 11 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. |
