Is readability the only difference?
I would say that this is a drier thing (do not repeat yourself).
If you look at the second sample, this is random:
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 ruin the terms, it just won’t do anything. - If the latter was an
else clause, you'd better put assert!(1 == 2) inside to make sure that it only executes if they are equal (and not because you made a mistake in the previous conditions). - And even then you will have a repetition between
1 < 2 and 1 > 2 .
Compare this to 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 the case, it is guaranteed to be comprehensive.
- A condition is recorded only once; there is no need to “cancel” it or something else.
Therefore, if vs match really depends on the number of different outputs:
- use
if if there is one or two branches, - use
match if there are three branches or more.
A match is simply more convenient than the if / else chain.
Note. I personally think cmp rarely used directly. This is more understood as an implementation device that allows you to implement one function to get all 4 inequality operators. Coming from C ++, this is a relief ...
source share