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

needless_range_loop suggests using iter on a value that do not have iter method #1014

Closed
malbarbo opened this issue Jun 15, 2016 · 5 comments
Labels
C-bug Category: Clippy is not doing the correct thing E-medium Call for participation: Medium difficulty level problem and requires some initial experience. T-middle Type: Probably requires verifiying types

Comments

@malbarbo
Copy link

In this example:

use std::ops::Index;

struct S(Vec<u32>);

impl Index<usize> for S {
    type Output = u32;

    fn index(&self, index: usize) -> &u32 {
        &self.0[index]
    }
}

fn main() {
    let s = S(vec![1, 2, 3]);

    for i in 0..3 {
        println!("{:?}", s[i]);
    }
}

Clippy says "Consider using for item in s.iter().take(3), but s does not have iter method.

@mcarton mcarton added C-bug Category: Clippy is not doing the correct thing E-medium Call for participation: Medium difficulty level problem and requires some initial experience. T-middle Type: Probably requires verifiying types labels Jun 15, 2016
@mcarton
Copy link
Member

mcarton commented Jun 15, 2016

I guess being indexable but not iterable is so uncommon no one ever noticed 😓

@llogiq
Copy link
Contributor

llogiq commented Jun 16, 2016

Maybe we should suggest implementing an .iter() function for something that has a .len() and is Indexable?

@mcarton
Copy link
Member

mcarton commented Jun 16, 2016

Why the len? Iterators need not to be finite.

@llogiq
Copy link
Contributor

llogiq commented Jun 16, 2016

True. Perhaps we should only require Index<usize> then.

@tnielens
Copy link
Contributor

tnielens commented Jul 21, 2020

The example isn't linted anymore.

The check early returns when the type has no .iter() method:

                // don't lint if the container that is indexed does not have .iter() method
                let has_iter = has_iter_method(cx, indexed_ty);
                if has_iter.is_none() {
                    return;
                }

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 E-medium Call for participation: Medium difficulty level problem and requires some initial experience. T-middle Type: Probably requires verifiying types
Projects
None yet
Development

No branches or pull requests

5 participants