False positive iterating over and ignoring 0..n + 1

Open
#11,719 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
42/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
rust
Domain
tooling

Research direction

Start by locating the range_plus_one lint and its existing tests, then run the supplied Rust reproducer and the analogous map example. Done means the 0..n + 1 forms no longer produce the reported warning while the lint's intended cases remain covered by tests.

Written by the indexing model from the issue text.

Description

C-bug I-false-positive
Summary

The idiomatic way to do the same thing k times is

for _ in 0..k {
    do_thing();
}

Suppose k is the expression n + 1.

for _ in 0..n + 1 {
    do_thing();
}

This now triggers the range_plus_one lint, but

for _ in 0..=n {
    do_thing();
}

is much less clear about what's going on.

(0..n + 1).map(|_| f()) is similar.

Lint Name

range_plus_one

Reproducer

I tried this code:

fn foo(n: usize) {
    for _ in 0..n + 1 {
        println!("foo");
    }
}

with the pedantic group enabled.

I saw this happen:

warning: an inclusive range would be more readable

I expected to see this happen:

[no warning]

Version
rustc 1.73.0 (cc66ad468 2023-10-03)
binary: rustc
commit-hash: cc66ad468955717ab92600c770da8c1601a4ff33
commit-date: 2023-10-03
host: x86_64-unknown-linux-gnu
release: 1.73.0
LLVM version: 17.0.2
Additional Labels

No response

Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from rust-lang/rust-clippy

All issues in rust-lang/rust-clippy

Similar issues

More Rust issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.