Why false<true work but can't compile true<false

Dear bro:
I am a new learner, I facing below 2 issue:

  1. why the result of (true, 3) < (false, 4)); is false ?
  2. compile issue: why false<true can pass but not true<false ?

below is the code, thanks for help.

    println!("{:?}", (true, 3) < (true, 4)); //true
    println!("{:?}", (true, 3) < (false, 4)); // false
    println!("{:?}", (false, 3) < (true, 4)); //true
    println!("{:?}", (false, 3) < (false, 4)); //true
    println!("{:?}", (3) < (4)); //true
    println!("{:?}", (false) < (true)); //true, can compile
    println!("{:?}", (true) < (false)); // can't compile 

It does compile successfully (e.g. using cargo check or cargo run), it just hits a deny-by-default clippy lint.

    Checking playground v0.0.1 (/playground)
error: this comparison involving the minimum or maximum element for this type contains a case that is always true or always false
 --> src/main.rs:8:22
  |
8 |     println!("{:?}", (true) < (false)); // can't compile
  |                      ^^^^^^^^^^^^^^^^
  |
  = help: because `(true)` is the maximum value for this type, this comparison is always false
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#absurd_extreme_comparisons
  = note: `#[deny(clippy::absurd_extreme_comparisons)]` on by default

This lint is supposed to catch bogus comparisons that are always true or always false such as e.g. for unsigned integers x < 0 or x >= 0; it’s deny-by-default, because such a comparison appearing in practical code is a bug in most cases.

If necessary, you can turn this particular lint into a warning with #![warn(clippy::absurd_extreme_comparisons)], or perhaps turn all (current) deny-by-default clippy lints into warnings with #![warn(clippy::correctness)]. (You can even completely remove the warning with allow(…) instead of warn(…).)


The comparison of pairs works via the logic that (a, b) < (c, d) is true if a < c, or if a == c and b < d. This is also called “lexicographic” ordering, since it’s the way that 2-letter words are ordered in a dictionary: in comes before on because i < o (alphabetically), and in comes before is because when the first letter is equal, we compare the next, and n < s (alphabetically).

Longer tuples, or structs with derive(PartialOrd) use lexicographic ordering (with potentially more fields), too; e.g. tuples (T1, T2, T3) compare similar to 3-letter words, and so on.

9 Likes

I am clear now, thank you so much.

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.