Macro one_of::case[][src]

macro_rules! case {
    ($d x:expr, $($d ($d $p:pat $d (if $d $g:expr)? => $d $b:block)+ ;)+) => { ... };
    ($d x:expr, $($d ($d $p:pat $d (if $d $g:expr)? => $d $b:block)+ ;)+) => { ... };
    ($d x:expr, $($d ($d $p:pat $d (if $d $g:expr)? => $d $b:block)+ ;)+) => { ... };
    ($d x:expr, $($d ($d $p:pat $d (if $d $g:expr)? => $d $b:block)+ ;)+) => { ... };
    ($d x:expr, $($d ($d $p:pat $d (if $d $g:expr)? => $d $b:block)+ ;)+) => { ... };
    ($d x:expr, $($d ($d $p:pat $d (if $d $g:expr)? => $d $b:block)+ ;)+) => { ... };
    ($d x:expr, $($d ($d $p:pat $d (if $d $g:expr)? => $d $b:block)+ ;)+) => { ... };
    ($d x:expr, $($d ($d $p:pat $d (if $d $g:expr)? => $d $b:block)+ ;)+) => { ... };
    ($d x:expr, $($d ($d $p:pat $d (if $d $g:expr)? => $d $b:block)+ ;)+) => { ... };
    ($d x:expr, $($d ($d $p:pat $d (if $d $g:expr)? => $d $b:block)+ ;)+) => { ... };
    ($d x:expr, $($d ($d $p:pat $d (if $d $g:expr)? => $d $b:block)+ ;)+) => { ... };
}

Pattern matching against one_of types, similar to match

Groups of match arms are separated by ;

Unlike match, case only accepts blocks as values of match arms

Examples

matching against one of the integer types

use one_of::{case, one_of};
case!(<one_of!(i8, i64, u8, u64)>::from(42u64),
    // i8
    _ => {
        panic!("not i8");
    };

    // i64
    _ => {
        panic!("not i64");
    };

    // u8
    _ => {
        panic!("not u8");
    };

    // u64
    0 ..= 41 => {
        panic!("not less than 42");
    }
    n => {
        assert_eq!(n, 42);
    };
);

gaurds are also supported, just like match

case!(<one_of!(bool, &str, i64)>::from("Hello, world!"),
    // bool
    _ => {
        panic!("not bool");
    };

    // &str
    s if s.starts_with("Hello, ") => {
        assert_eq!(&s[7 ..], "world!");
    }
    _ => {
        panic!("not other strings");
    };

    // i64
    _ => {
        panic!("not i64");
    };
);

this is the equivalent using match and a custom enum

enum BoolStrOrInt<'a> {
    Bool(bool),
    Str(&'a str),
    Int(i64),
}

match BoolStrOrInt::Str("Hello, world!") {
    // bool
    BoolStrOrInt::Bool(_) => {
        panic!("not bool");
    }

    // &str
    BoolStrOrInt::Str(s) if s.starts_with("Hello, ") => {
        assert_eq!(&s[7 ..], "world!");
    }
    BoolStrOrInt::Str(_) => {
        panic!("not other strings");
    }

    // i64
    BoolStrOrInt::Int(_) => {
        panic!("not i64");
    }
}