Skip to content

missing_asserts_for_indexing understands assert!(x.len()==2) but not assert_eq!(x.len(), 2) #14255

@tv42

Description

@tv42

Summary

missing_asserts_for_indexing is saying to get bounds checking done up-front, I should add an assert on the length of the slice. Great.

Because I happen to be writing a test, I know exactly the length, and chose to write an equality and not a > check.

Generally, assert_eq! is to be preferred over assert!(a == b), so I used that.

Clippy didn't recognize that as satisfactory, and the warning is still there. Adding assert!(s.len() == 2) right next to the other assert silences Clippy.

Either one should have been enough.

Lint Name

missing_asserts_for_indexing

Reproducer

I tried this code:

#![warn(clippy::missing_asserts_for_indexing)]

fn main() {
    let demo = &["foo", "bar"][..];

    // This is not enough
    assert_eq!(demo.len(), 2);
    // However, this is
    // assert!(demo.len() == 2);
    assert_eq!(demo[0], "foo");
    assert_eq!(demo[1], "bar");
}

I saw this happen:

$ cargo clippy
warning: indexing into a slice multiple times without an `assert`
  --> src/main.rs:10:16
   |
10 |       assert_eq!(demo[0], "foo");
   |  ________________^
11 | |     assert_eq!(demo[1], "bar");
   | |______________________^
   |
   = help: consider asserting the length before indexing: `assert!(demo.len() > 1);`
note: slice indexed here
  --> src/main.rs:10:16
   |
10 |     assert_eq!(demo[0], "foo");
   |                ^^^^^^^
note: slice indexed here
  --> src/main.rs:11:16
   |
11 |     assert_eq!(demo[1], "bar");
   |                ^^^^^^^
   = note: asserting the length before indexing will elide bounds checks
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#missing_asserts_for_indexing
note: the lint level is defined here
  --> src/main.rs:1:9
   |
1  | #![warn(clippy::missing_asserts_for_indexing)]
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

warning: `clippy-missing_asserts_for_indexing-assert_eq` (bin "clippy-missing_asserts_for_indexing-assert_eq") generated 1 warning
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00

I expected to see this happen:

No warning, behave like with the commented-out assert!(demo.len() == 2);.

Version

rustc 1.84.1 (e71f9a9a9 2025-01-27)
binary: rustc
commit-hash: e71f9a9a98b0faf423844bf0ba7438f29dc27d58
commit-date: 2025-01-27
host: x86_64-unknown-linux-gnu
release: 1.84.1
LLVM version: 19.1.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