try_match
Provides expression macros to match a pattern on a given expression.
Basic Usage
Macros
use ;
use ;
// `try_match!` returns `Result`: `Ok(bindings)` on success or
// `Err(input_value)` otherwise
assert_eq!;
assert_eq!;
// `match_ok!` returns `Option`
assert_eq!;
assert_eq!;
// `unwrap_match!` panics on failure:
assert_eq!;
unwrap_match!; // will panic
Bindings
// Returns `()` (wrapped by `Ok(_)`) if there are no bound variables
assert_eq!;
// ... the bound value if there is exactly one binding
assert_eq!;
// ... an anonymous struct if there are multiple bindings
let vars = unwrap_match!;
assert_eq!;
// ... or a tuple if the binding names are numeric
let = unwrap_match!;
assert_eq!;
// An optional `=>` clause specifies an explicit mapping
assert_eq!;
assert_eq!;
Partial Application
// Omit the scrutinee expression to produce a closure
let _: = match_ok!;
let _: fn = match_ok!;
Applications
Iterator::filter_map
let array = ;
let filtered: = array
.iter
.filter_map
.collect;
assert_eq!;
Iterator::map + Fallible Iterator::collect
let array = ;
let filtered: = array
.iter
.map
.collect;
// `Var2` is the first value that doesn't match
assert_eq!;
Extract Variants
let enums = ;
assert_eq!;
assert_eq!;
assert!;
assert!;
Expect Certain Variants
this_fn_expects_var1;
Related Works
matcher::matches! (now incorporated into the standard library as
core::matches!) is similar but only returns bool indicating whether
matching was successful or not.
let success1 = matches!;
let success2 = match_ok!.is_some;
assert_eq!;
bind_match::bind_match! and extract::extract! behave in the same way
as match_ok! except for the lack of implicit mapping and partial application.
variant::get_variant! from the extract_variant crate offers a similar
functionality to match_ok!. It supports implicit mapping but uses different
rules to handle multiple bindings.
License
MIT/Apache-2.0