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.");
}
}
- There is no
else
clause. If you mess up the conditions it'll just do nothing.
- If the last one was an
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).
- And even then you would still have a repetition between
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."),
}
}
- You cannot accidentally forget a case, it's guaranteed to be exhaustive.
- The condition is only written once, no need to "reverse" it or anything.
Therefore, if
vs match
is a matter of number of different outputs really:
- use
if
if there is one or two branches,
- use
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...