[][src]Macro sum_type::defer

macro_rules! defer {
    ($kind:ident as $variable:expr; $( $variant:ident )|* => |ref $item:ident| $exec:expr) => { ... };
    ($kind:ident as $variable:expr; $( $variant:ident )|* => |ref mut $item:ident| $exec:expr) => { ... };
    (@foreach_variant $kind:ident, $variable:expr; $( $pattern:pat => $exec:expr ),*) => { ... };
}

Execute an operation on each enum variant.

This macro is short-hand for matching on each variant in an enum and performing the same operation to each.

It will expand to roughly the following:

sum_type::sum_type! {
    #[derive(Debug, PartialEq)]
    pub enum Foo {
        First(u32),
        Second(f64),
        Third(String),
    }
}

let third = Foo::Third(String::from("Hello World"));

let got = match third {
    Foo::First(ref item) => item.to_string(),
    Foo::Second(ref item) => item.to_string(),
    Foo::Third(ref item) => item.to_string(),
};

Examples

sum_type::sum_type! {
    #[derive(Debug, PartialEq)]
    pub enum Foo {
        First(u32),
        Second(f64),
        Third(String),
    }
}

let mut third = Foo::Third(String::from("Hello World"));

// Execute some operation on each variant (skipping Second) and get the
// return value
let mut got = sum_type::defer!(Foo as third; First | Third => |ref item| item.to_string());

assert_eq!(got, "Hello World");

// mutate the variant in place
sum_type::defer!(Foo as third;
    First | Second | Third => |ref mut item| {
        *item = Default::default();
    }
);
assert_eq!(third, Foo::Third(String::new()));

The defer!() macro will panic if it encounters an unhandled variant.

sum_type::sum_type! {
    #[derive(Debug, PartialEq)]
    pub enum Foo {
        First(u32),
        Second(f64),
        Third(String),
    }
}

let mut first = Foo::First(42);

sum_type::defer!(Foo as first; Second | Third => |ref _dont_care| ());