Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use `std::cmp::ordering` instead of an `if` statement in Rust

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.");
    }
}
like image 218
kangaroo Avatar asked Jan 04 '18 11:01

kangaroo


1 Answers

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.");
    }
}
  1. There is no else clause. If you mess up the conditions it'll just do nothing.
  2. 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).
  3. 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."),
    }
}
  1. You cannot accidentally forget a case, it's guaranteed to be exhaustive.
  2. 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...

like image 82
Matthieu M. Avatar answered Nov 09 '22 16:11

Matthieu M.