Provides an expression macro try_match
that performs pattern
matching and returns the bound variables via Ok(_)
iff successful.
```rust use trymatch::trymatch;
enum Enum
// The right-hand side of =>
if successful
asserteq!(trymatch!(Var1(x) = Var1(42) => x), Ok(42));
asserteq!(trymatch!(Var2 = Var2::
// Err(input)
on failure
asserteq!(trymatch!(Var1(x) = Var2::
=>
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):
``rust
//
()` if there are no bound variables
asserteq!(trymatch!(Var1(_) = Var1(42)), Ok(()));
// The bound variable if there is exactly one bound variables asserteq!(trymatch!(Var1(x) = Var1(42)), Ok(42));
// An anonymous struct if there are multiple bound variables let vars = trymatch!(Var1((a, b)) = Var1((12, 34))).unwrap(); asserteq!((vars.a, vars.b), (12, 34)); ```
It produces a tuple if you name the bound variables like _0
, _1
, _2
,
...:
rust
let (a, b) = try_match!(Var1((_0, _1)) = Var1((12, 34))).unwrap();
assert_eq!((a, b), (12, 34));
It's an error to specify non-contiguous binding indices:
rust
let _ = try_match!(Var1((_0, _2)) = Var1((12, 34)));
rust
let _ = try_match!(Var1((_0, _9223372036854775808)) = Var1((12, 34)));
matches
[matches!
] is similar but only returns bool
indicating whether matching
was successful or not.
rust
let success1 = matches!(Var1(42), Var1(_));
let success2 = try_match!(Var1(_) = Var1(42)).is_ok();
License: MIT/Apache-2.0