Closed
Description
Hello! I'm just learning rust and clippy has been a valuable resource for improving my code, thanks!
Today I got confused by one of the clippy suggestions.
I had a look at the source but not sure how to implement proposed improvements.
Consider the following
fn load_rom(&mut self, data: &[u8]) {
let min = self.get_offset();
let max = min + data.len();
let mut rom_pos = 0;
for i in min..max {
self.memory[i] = data[rom_pos];
rom_pos += 1;
}
}
clippy gives the following warning:
warning: the variable `rom_pos` is used as a loop counter. Consider using `for (rom_pos, item) in min..max.enumerate()` or similar iterators
--> src/cpu.rs:546:9
|
546 | for i in min..max {
| _________^ starting here...
547 | | self.memory[i] = data[rom_pos];
548 | | rom_pos += 1;
549 | | }
| |_________^ ...ending here
|
= note: #[warn(explicit_counter_loop)] on by default
= help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#explicit_counter_loop
attempting to rework the code as suggested:
for (rom_pos, i) in min..max.enumerate() {
self.memory[i] = data[rom_pos];
}
... does not compile:
error: no method named `enumerate` found for type `usize` in the current scope
--> src/cpu.rs:552:38
|
552 | for (rom_pos, i) in min..max.enumerate() {
| ^^^^^^^^^
|
= note: the method `enumerate` exists but the following trait bounds were not satisfied: `usize : std::iter::Iterator`
error[E0308]: mismatched types
--> src/cpu.rs:552:13
|
552 | for (rom_pos, i) in min..max.enumerate() {
| ^^^^^^^^^^^^ expected usize, found tuple
|
= note: expected type `usize`
found type `(_, _)`
Eventually I realized I just need to wrap the min..max in parenthesis to solve it.
I feel an improved error message in check_for_loop_explicit_counter could look like this:
warning: the variable `rom_pos` is used as a loop counter.
Consider using `for (rom_pos, i) in (min..max).enumerate()`
Also it hardcodes "item" rather than using the variable name "i"