From 04b184591bb53035d2579eef8206d2e3d09cfc60 Mon Sep 17 00:00:00 2001 From: Nikolai Vazquez Date: Sun, 28 Jul 2019 16:46:18 -0700 Subject: [PATCH] Add `Either::map` --- src/lib.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 4f81162..8a4ccbb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -581,6 +581,26 @@ impl Either { pub fn into_inner(self) -> T { either!(self, inner => inner) } + + /// Map `f` over the contained value and return the result in the + /// corresponding variant. + /// + /// ``` + /// use either::*; + /// + /// let value: Either<_, i32> = Right(42); + /// + /// let other = value.map(|x| x * 2); + /// assert_eq!(other, Right(84)); + /// ``` + pub fn map(self, f: F) -> Either + where F: FnOnce(T) -> M + { + match self { + Left(l) => Left(f(l)), + Right(r) => Right(f(r)), + } + } } /// Convert from `Result` to `Either` with `Ok => Right` and `Err => Left`.