Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrong recommendation for needless_range_loop if loop variable is used in closure #2542

Closed
vbrandl opened this issue Mar 17, 2018 · 0 comments · Fixed by #5798
Closed

Wrong recommendation for needless_range_loop if loop variable is used in closure #2542

vbrandl opened this issue Mar 17, 2018 · 0 comments · Fixed by #5798
Labels
C-bug Category: Clippy is not doing the correct thing

Comments

@vbrandl
Copy link

vbrandl commented Mar 17, 2018

Clippy falsely warns about a needless range loop, if the loop variable is (aside from indexing) only used inside a closure. The following example triggers the false positive:

fn option() -> Option<bool> {
    unimplemented!()
}

fn error(idx: usize) -> () {
    unimplemented!()
}

fn test(len: usize) {
    let mut arr = Vec::with_capacity(len);
    for idx in 0..len {
        arr[idx] = option().ok_or_else(|| error(idx)).unwrap();
    }
}

This could be written as

fn test(len: usize) {
    let mut arr = Vec::with_capacity(len);
    for (idx, val) in arr.iter_mut().take(len).enumerate() {
        *val = option().ok_or_else(|| error(idx)).unwrap();
    }
}

But clippy says to use for <item> in arr.iter_mut().take(len) {

Tested with rustc 1.25.0-nightly (3ec5a99aa 2018-02-14) and clippy 0.0.186.

@vbrandl vbrandl changed the title False positive for needless_range_loop if loop variable is used in closure Wrong recommendation for needless_range_loop if loop variable is used in closure Mar 17, 2018
@phansch phansch added the C-bug Category: Clippy is not doing the correct thing label Apr 1, 2018
bors added a commit that referenced this issue Feb 12, 2019
Fix `needless_range_loop` bad suggestion

Detect if the index variable is used inside a closure.

Fixes #2542
bors added a commit that referenced this issue Jul 14, 2020
Add test for `needless_range_loop` issue

Closes #2277

This was fixed when we fixed #2542.

changelog: none
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-bug Category: Clippy is not doing the correct thing
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants