Crate if_chain [] [src]

This crate provides a single macro called if_chain!.

if_chain! lets you write long chains of nested if and if let statements without the associated rightward drift. It also supports disjunctive patterns (e.g. if let Foo(a) | Bar(a) = b) in places where Rust would normally not allow them.

Examples

Basic example

if_chain! {
    if let Some(y) = x;
    if y.len() == 2;
    if let Some(z) = y;
    then {
        do_stuff_with(z);
    }
}

becomes

if let Some(y) = x {
    if y.len() == 2 {
        if let Some(z) = y {
            do_stuff_with(z);
        }
    }
}

Fallback values with else

if_chain! {
    if let Some(y) = x;
    if let Some(z) = y;
    then {
        do_stuff_with(z)
    } else {
        do_something_else()
    }
}

becomes

if let Some(y) = x {
    if let Some(z) = y {
        do_stuff_with(z)
    } else {
        do_something_else()
    }
} else {
    do_something_else()
}

Intermediate variables with let

if_chain! {
    if let Some(y) = x;
    let z = y.some().complicated().expression();
    if z == 42;
    then {
       do_stuff_with(y);
    }
}

becomes

if let Some(y) = x {
    let z = y.some().complicated().expression();
    if z == 42 {
        do_stuff_with(y);
    }
}

Disjunctive patterns

if_chain! {
    if let Foo(y) | Bar(y) | Baz(y) = x;
    let Bubbles(z) | Buttercup(z) | Blossom(z) = y;
    then { do_stuff_with(y) }
}

becomes

match x {
    Foo(y) | Bar(y) | Baz(y) => match y {
        Bubbles(z) | Buttercup(z) | Blossom(z) => do_stuff_with(z)
    },
    _ => {}
}

Note that if you use a plain let, then if_chain! assumes that the pattern is irrefutable (always matches) and doesn't add a fallback branch.

Macros

if_chain

Macro for writing nested if let expressions.