Description
With code like
use std::fmt::Debug;
pub fn test<T: Debug>(x: Vec<T>) {
for t in x.iter() {
println!("{:?}", t);
}
for t in x.into_iter() {}
}
clippy complains
warning: it is more idiomatic to loop over references to containers instead of using explicit iteration methods
--> src/main.rs:4:14
|
4 | for t in x.iter() {
| ^^^^^^^^ help: to write this more concisely, try: `&x`
|
= note: #[warn(explicit_iter_loop)] on by default
= help: for further information visit https://rust-lang-nursery.github.io/rust-clippy/v0.0.212/index.html#explicit_iter_loop
warning: it is more idiomatic to loop over containers instead of using explicit iteration methods`
--> src/main.rs:8:14
|
8 | for t in x.into_iter() {}
| ^^^^^^^^^^^^^ help: to write this more concisely, try: `x`
|
= note: #[warn(explicit_into_iter_loop)] on by default
= help: for further information visit https://rust-lang-nursery.github.io/rust-clippy/v0.0.212/index.html#explicit_into_iter_loop
I think this is counter-productive. I always use iter
, into_iter
or iter_mut
when iterating on a Vec
to document whether the iterated-over variable has type &T
, T
or &mut T
, respectively. I find it much harder to see this when the indication is just a sigil in front of the vector. Essentially I use these three methods as "type ascription" whenever I am in doubt, and only do for ... in x
when I do not really care. (I am aware that I could accidentally use x.into_iter()
on a &Vec
, and think linting against that like clippy does is a good idea -- though it should suggest x.iter()
, not &x
.)
The lint website just says "readability". I wonder on which basis for ... in &x
was deemed more readable than for ... in x.iter()
? I will always prefer the latter, and would even enable a lint against the former.
Maybe it is just a small minority that feels like I do, but with the growing popularity of Clippy I feel we should at least have a discussion about this instead of just decreeing a certain coding style without justification. :) I am not sure what the right venue for such a discussion is, though.
As far as I am concerned, this bug would be fixed if the lint changed to allow-by-default. I might at some point send in a feature request to lint in the opposite direction. ;) Alternatively, if the majority of people agrees with the lint, then so be it -- but then at least we have had that discussion.