#macro #pattern #match

bind_match

Convenience macro similar to matches! but binds to variables in the pattern and returns an Option of the result

3 releases

0.1.2 Jan 6, 2021
0.1.1 Jan 6, 2021
0.1.0 Jan 3, 2021

#843 in Rust patterns

Download history 590/week @ 2022-01-24 358/week @ 2022-01-31 283/week @ 2022-02-07 153/week @ 2022-02-14 297/week @ 2022-02-21 156/week @ 2022-02-28 104/week @ 2022-03-07 121/week @ 2022-03-14 107/week @ 2022-03-21 86/week @ 2022-03-28 111/week @ 2022-04-04 39/week @ 2022-04-11 84/week @ 2022-04-18 70/week @ 2022-04-25 66/week @ 2022-05-02 33/week @ 2022-05-09

256 downloads per month
Used in 3 crates (via narui_macros)

MIT license

5KB

bind_match

Convenience macro similar to matches! but lets you bind to and pattern and return an Option of the result.

The input of the macro looks like this:

bind_match!(input_expr, pattern => binding_expr)

Or with pattern guards:

bind_match!(input_expr, pattern if guard => binding_expr)

The binding_expr is returned, with variables bound in the pattern.

Example

This can be particularly useful when matching inside iterator adapters.

use bind_match::bind_match;

enum Foo {
    A(Option<i32>, bool),
    B { open: bool, closed: bool },
}
struct Bar {
    foo: Foo,
    fun: bool,
}

fn fun_when_open(bars: impl IntoIterator<Item = Bar>) -> Option<bool> {
    bars.into_iter()
        .filter_map(|bar| bind_match!(bar, Bar { foo: Foo::B { open, .. }, fun } if open => fun ))
        .next()
}

No runtime deps