Skip to content

Incorrect clippy::op_ref warning on &s[0] #4645

@jsgf

Description

@jsgf

Given the code:

pub fn inrange<T: Ord>(s: &[T], n: &T) -> bool {
    s.last().map_or(false, |last| &s[0] <= n && n <= last)
}

Clippy warns:

 --> src/lib.rs:2:35
  |
2 |     s.last().map_or(false, |last| &s[0] <= n && n <= last)
  |                                   -----^^^^^
  |                                   |
  |                                   help: use the left value directly: `s[0]`
  |
  = note: `#[warn(clippy::op_ref)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#op_ref

However, this is incorrect, as n has reference type &T. Changing it to s[0] <= n fails to compile:

error[E0308]: mismatched types
 --> src/lib.rs:2:43
  |
2 |     s.last().map_or(false, |last| s[0] <= n && n <= last)
  |                                           ^ expected type parameter, found &T
  |
  = note: expected type `T`
             found type `&T`
  = help: type parameters must be constrained to match other types
  = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions