When to use `std :: cmp :: ordering` instead of the` if` expression in Rust

When should I use std::cmp::ordering in a match block instead of using the if / else if ? Is readability the only difference?

For instance:

 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."); } } 
+5
source share
1 answer

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 ...

+7
source

Source: https://habr.com/ru/post/1274499/


All Articles