no-std if_chain

Macro for writing nested if let expressions

4 releases

0.1.3 Jul 20, 2018
0.1.2 Feb 17, 2017
0.1.1 Dec 29, 2016
0.1.0 Dec 28, 2016

#9 in Rust patterns

Download history 6589/week @ 2018-05-06 8701/week @ 2018-05-13 8360/week @ 2018-05-20 8158/week @ 2018-05-27 9524/week @ 2018-06-03 8966/week @ 2018-06-10 7086/week @ 2018-06-17 7965/week @ 2018-06-24 9246/week @ 2018-07-01 8343/week @ 2018-07-08 9358/week @ 2018-07-15 9818/week @ 2018-07-22 7654/week @ 2018-07-29

36,654 downloads per month

if_chain

Build Status Cargo

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 multiple patterns (e.g. if let Foo(a) | Bar(a) = b) in places where Rust would normally not allow them.

For more information on this crate, see the documentation and associated blog post.


lib.rs:

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 multiple patterns (e.g. if let Foo(a) | Bar(a) = b) in places where Rust would normally not allow them.

See the associated blog post for the background behind this crate.

Note about recursion limits

If you run into "recursion limit reached" errors while using this macro, try adding

#![recursion_limit = "1000"]

to the top of your crate.

Examples

Quick start

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);
    }
}

Multiple patterns

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

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.

MIT/Apache-2.0 license
  • No runtime deps

Reverse deps