When should I use std::cmp::ordering
in a match
block instead of using an if
/else if
statement? Is readability the only difference?
For example:
use std::cmp::Ordering;
fn main() {
match 2.cmp(&2) {
Ordering::Less => println!("Less than 2."),
Ordering::Greater => println!("Greater than 2."),
Ordering::Equal => println!("Equal to 2."),
}
}
vs.
fn main() {
if 1 < 2 {
println!("less than 2.");
} else if 1 > 2 {
println!("Greater than 2.");
} else if 1 == 2 {
println!("Equal to 2.");
}
}
Is readability the only difference?
I would say it's more of a DRY (Don't Repeat Yourself) thing.
If you look at the second sample, it's messy:
fn main() { if 1 < 2 { println!("less than 2."); } else if 1 > 2 { println!("Greater than 2."); } else if 1 == 2 { println!("Equal to 2."); } }
else
clause. If you mess up the conditions it'll just do nothing.else
clause, you'd still better put an assert!(1 == 2)
inside to make sure that it's only taken when the two are equal (and not because you made a mistake in the previous conditions).1 < 2
and 1 > 2
.Compare that to the match
:
fn main() { match 2.cmp(&2) { Ordering::Less => println!("Less than 2."), Ordering::Greater => println!("Greater than 2."), Ordering::Equal => println!("Equal to 2."), } }
Therefore, if
vs match
is a matter of number of different outputs really:
if
if there is one or two branches,match
if there are three branches or more.A match
is just more maintainable than an if
/else
chain.
Note: I personally think that cmp
is rarely used directly. It is more meant as an implementation device, allowing you to implement a single function to get all 4 inequality operators. Coming from C++, it's a relief...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With