What are those Less/Greater/Equal symbols that matches cmp::Ordering::* but with the exact opposite meaning?

That must be a compiler bug no?????

fn main() { 
    match 2.cmp(&1) {
        Less => println!("surprise less"),
        Greater => println!("ok"),
        Equal => println!("surprise equals"),
    }

=> Output "surprise"

playground

The compiler warns you what's going on here:

warning[E0170]: pattern binding `Less` is named the same as one of the variants of the type `std::cmp::Ordering`
 --> src/main.rs:5:9
  |
5 |         Less => println!("Surprise !!!!!!!!!!!!"),
  |         ^^^^ help: to match on the variant, qualify the path: `std::cmp::Ordering::Less`
  |
  = note: `#[warn(bindings_with_variant_name)]` on by default

To match the value std::cmp::Ordering::Less, you need to write it out that way, or use std::cmp::Ordering::*; in pattern context (on the left side of =>), Less is interpreted as a wildcard, as if you'd written

match 2.cmp(&1) {
    whatever => ...,
}

This is because there's no value named Less in scope.

(It's not a bad idea to add the line

#![deny(bindings_with_variant_name)]

to your lib.rs or main.rs, so that you'll get a hard compiler error if you accidentally do this.)

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.