try_match
Provides an expression macro try_match
that performs pattern
matching and returns the bound variables via Ok(_)
iff successful.
Examples
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!;
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 variable
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!;
It's an error to specify non-contiguous binding indices:
let _ = try_match!;
let _ = try_match!;
Restrictions
- Macros cannot be used in a supplied pattern.
Related Work: matches
matches!
is similar but only returns bool
indicating whether matching
was successful or not.
let success1 = matches!;
let success2 = try_match!.is_ok;
License: MIT/Apache-2.0