Skip to content

clippy::indexing_slicing triggers when using an index returned by binary search #14452

Open
@lopopolo

Description

@lopopolo

Summary

Indexes returned by <[_]>::binary_search, <[_]>::binary_search_by, and <[_]>::binary_search_by_key always return an index within the slice if they return Ok(_).

Lint Name

clippy::indexing_slicing

Reproducer

I tried this code:

#[deny(clippy::indexing_slicing)]
pub fn get_val(s: &[i32]) -> Option<i32> {
    let Ok(idx) = s.binary_search(&3) else {
        return None;
    };
    Some(s[idx])
}

I saw this happen:

Standard Error
    Checking playground v0.0.1 (/playground)
error: indexing may panic
 --> src/lib.rs:6:10
  |
6 |     Some(s[idx])
  |          ^^^^^^
  |
  = help: consider using `.get(n)` or `.get_mut(n)` instead
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#indexing_slicing
note: the lint level is defined here
 --> src/lib.rs:1:8
  |
1 | #[deny(clippy::indexing_slicing)]
  |        ^^^^^^^^^^^^^^^^^^^^^^^^

error: could not compile `playground` (lib) due to 1 previous error

I expected to see this happen:

No lint violation

Version

rust 1.85.1

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions