try_match
Provides an expression macro try_match
that matches a pattern on a given
expression and returns the bound variables in Ok(_)
if successful.
Basic Usage
Explicit Mapping
use try_match;
use ;
// The right-hand side of `=>` if successful
assert_eq!;
assert_eq!;
// `Err(input)` on failure
assert_eq!;
assert_eq!;
// Supports `if` guard
assert_eq!;
Implicit Mapping
=>
and the part that comes after can be omitted (requires implicit_map
feature, which is enabled by default; you can disable it to skip the
compilation of the internal procedural macro):
// `()` if there are no bound variables
assert_eq!;
// The bound variable if there is exactly one bound variables
assert_eq!;
assert_eq!;
// An anonymous struct if there are multiple bound variables
let vars = try_match!.unwrap;
assert_eq!;
It produces a tuple if you name the bound variables like _0
, _1
, _2
,
...:
let = try_match!.unwrap;
assert_eq!;
try_match!.unwrap_err;
It's an error to specify non-contiguous binding indices:
let _ = try_match!;
let _ = try_match!;
Quirks
When using implicit mapping, bind variables defined inside macros are
not recognized because at the point of try_match
's macro expansion,
inner macros are not expended yet.
This macro moves a value out of the place represented by the input expression to return it on failure. Make sure to pass a reference if this is not desired.
let array = ;
// ERROR: Can't move out of `array[0]`
let _: &UncopyValue = try_match!.unwrap;
let _: &UncopyValue = try_match!.unwrap;
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 Work
matcher::matches!
(now incorporated into the standard library as
core::matches!
) is similar but only returns bool
indicating whether
matching was successful or not.
if_rust_version!
bind_match::bind_match!
and extract::extract!
use the same
syntax (except for implicit mapping) but return Some(expr)
on success
instead.
License: MIT/Apache-2.0