Skip to content

indexing_slicing displays error when indexing reference to array #6021

@Zenithsiz

Description

@Zenithsiz

I tried this code:

#![warn(clippy::indexing_slicing)]

pub fn f(arr: &[u32; 2]) {
    let _a = arr[0];
}

Playground

I expected to see this happen:

No warning displayed, as arr[0] is known to exist, because arr has 2 elements.

Instead, this happened:

I got the warning:

warning: indexing may panic.
 --> src/lib.rs:4:14
  |
4 |     let _a = arr[0];
  |              ^^^^^^
  |
note: the lint level is defined here
 --> src/lib.rs:1:9
  |
1 | #![warn(clippy::indexing_slicing)]
  |         ^^^^^^^^^^^^^^^^^^^^^^^^
  = 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

At first I thought that perhaps arr[0] would use <[u8]>::index and so it could panic and clippy was correct, but when building the assembly, even in debug mode, there is no panic code, and using an invalid index triggers a rustc error about the operation always panicking at runtime, so I believe clippy should also detect when this is valid.

Meta

  • cargo clippy -V: e.g. clippy 0.0.212 (2020-09-08 5099914)

As this is on the playground, I am unable to run rustc -Vv or provide a backtrace.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingC-enhancementCategory: Enhancement of lints, like adding more cases or adding help messagesE-mediumCall for participation: Medium difficulty level problem and requires some initial experience.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions