3

Add some core::cmp::Ordering helpers by jnqnfe · Pull Request #79656 · rust-lang...

 3 years ago
source link: https://github.com/rust-lang/rust/pull/79656
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Contributor

jnqnfe commented 17 days ago

...to allow easier equal-to-or-greater-than and less-than-or-equal-to
comparisons.

Prior to Rust 1.42 a greater-than-or-equal-to comparison might be written
either as a match block, or a traditional conditional check like this:

if cmp == Ordering::Equal || cmp == Ordering::Greater {
    // Do something
}

Which requires two instances of cmp. Don't forget that while cmp here
is very short, it could be something much longer in real use cases.

From Rust 1.42 a nicer alternative is possible:

if matches!(cmp, Ordering::Equal | Ordering::Greater) {
    // Do something
}

The commit adds another alternative which may be even better in some cases:

if cmp.is_equal_or_greater() {
    // Do something
}

The earlier examples could be cleaner than they are if the variants of
Ordering are imported such that Equal, Greater and Less can be
referred to directly, but not everyone will want to do that.

The new solution can shorten lines, help avoid logic mistakes, and avoids
having to import Ordering / Ordering::*.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK