Documentation
https://docs.rs/match-commutative
Motivation
When you need to match on three values that form a commutative math relation, you often need to
duplicate a lot of patterns.
Let's look at an example of what this might look like:
// imagine that these values come from somewhere and we need to match on them
let operant1 = Str;
let operant2 = Num;
let operator = Plus;
match
// Types that we use in this example
For both Operator::{Plus, Mult}, we have to write two patterns each that are exactly identical
(and connect them with | (or-pattern)) and execute the same logic.
The only difference in the pattern is the ordering of the Operant. Not nice!
Using match-commutative instead
With match-commutative this can be simplified to:
use match_commutative;
// imagine that these values come from somewhere and we need to match on them
let operant1 = Str;
let operant2 = Num;
let operator = Plus;
match_commutative!;
// Types that we use in this example
Note that in the above example the values of operant1 and operant2 could have been swapped, while still
leading to the same program output.
So we have successfully avoided the expression of ordering in our patterns
(where ordering is not needed between two Operants).✨
Using non_commut block for operants that are not commutative
If you need to match on operants that are not commutative, you can put the pattern
in the optional non_commut block. Within non_commut patterns behave exactly like std Rust:
use match_commutative;
let operant1 = Str;
let operant2 = Num;
let operator = Minus; // a non-commutative operator!
let result = match_commutative!;
assert_eq!;
// Types that we use in this example
Getting Started
In your Cargo.toml file add the following lines under [dependencies]:
= "0.1.0"
Safety
This crate is implemented in 100% Safe Rust, which is ensured by using #![forbid(unsafe_code)].
MSRV
The Minimum Supported Rust Version for this crate is 1.54. An increase of MSRV will be indicated by a minor change (according to SemVer).