From 29b3b63b404c6a2cec28ff5eb067efe0b054a37f Mon Sep 17 00:00:00 2001 From: Stefan Majewsky Date: Sun, 18 Oct 2026 19:33:33 +0200 Subject: add option.Option.Map() --- option/option.go | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'option/option.go') 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. -- cgit v1.3.1