Skip to content

indexing_slicing warns about using custom indexing operations #11525

Closed
@LunaBorowska

Description

@LunaBorowska

Summary

indexing_slicing warns about use of custom indexing operators that cannot possibly fail. I think it may make sense to check whether an indexed type has get method, and not report a problem if it doesn't.

This was initially reported to me on https://codeberg.org/xfix/enum-map/issues/78.

Lint Name

indexing_slicing

Reproducer

I tried this code:

#![warn(clippy::indexing_slicing)]

use std::ops::Index;

struct BoolMap<T> {
    false_value: T,
    true_value: T,
}

impl<T> Index<bool> for BoolMap<T> {
    type Output = T;
    fn index(&self, index: bool) -> &T {
        if index { &self.true_value } else { &self.false_value }
    }
}

fn main() {
    let map = BoolMap { false_value: 2, true_value: 4 };
    println!("{}", map[true]);
}

I saw this happen:

warning: indexing may panic
  --> src/main.rs:19:20
   |
19 |     println!("{}", map[true]);
   |                    ^^^^^^^^^
   |
   = 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/main.rs:1:9
   |
1  | #![warn(clippy::indexing_slicing)]
   |         ^^^^^^^^^^^^^^^^^^^^^^^^

I expected to see this happen:

No warning.

Version

rustc 1.72.0 (5680fa18f 2023-08-23)
binary: rustc
commit-hash: 5680fa18feaa87f3ff04063800aec256c3d4b4be
commit-date: 2023-08-23
host: x86_64-unknown-linux-gnu
release: 1.72.0
LLVM version: 16.0.5

Additional Labels

No response

Metadata

Metadata

Assignees

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