Skip to main content

for_both

Macro for_both 

Source
macro_rules! for_both {
    ($value:expr, $pattern:pat => $result:expr) => { ... };
    ($name:ident => $result:expr) => { ... };
}
Expand description

Evaluate the provided expression for both Either::Left and Either::Right.

This macro is useful in cases where both sides of Either can be interacted with in the same way even though the don’t share the same type.

Syntax:

  • either::for_both!( expression , pattern => expression )
  • either::for_both!( ident => expression )

Unlike map_both!, this macro converges both variants to the type returned by the expression.

§Example

use either::Either;

fn length(owned_or_borrowed: Either<String, &'static str>) -> usize {
    either::for_both!(owned_or_borrowed, s => s.len())
}

fn main() {
    let borrowed = Either::Right("Hello world!");
    let owned = Either::Left("Hello world!".to_owned());

    assert_eq!(length(borrowed), 12);
    assert_eq!(length(owned), 12);
}
use either::Either;

fn length(s: Either<String, Vec<u8>>) -> usize {
    either::for_both!(s => s.len())
}

fn main() {
    let string = Either::Left("Hello world!".to_owned());
    let bytes = Either::Right(b"Hello world!".to_vec());

    assert_eq!(length(string), 12);
    assert_eq!(length(bytes), 12);
}