Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add some core::cmp::Ordering helpers #79656

Merged
merged 1 commit into from
Dec 11, 2020
Merged

Add some core::cmp::Ordering helpers #79656

merged 1 commit into from
Dec 11, 2020

Commits on Dec 10, 2020

  1. Add some core::cmp::Ordering helpers

    ...to allow easier greater-than-or-equal-to and less-than-or-equal-to
    comparisons, and variant checking without needing to import the enum,
    similar to `Option::is_none()` / `Option::is_some()`, in situations where
    you are dealing with an `Ordering` value. (Simple `PartialOrd` / `Ord`
    based evaluation may not be suitable for all situations).
    
    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:
    
    ```rust
    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:
    
    ```rust
    if matches!(cmp, Ordering::Equal | Ordering::Greater) {
        // Do something
    }
    ```
    
    The commit adds another alternative which may be even better in some cases:
    
    ```rust
    if cmp.is_ge() {
        // 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::*`.
    jnqnfe committed Dec 10, 2020
    Configuration menu
    Copy the full SHA
    169c59f View commit details
    Browse the repository at this point in the history