iteratorrustrust-cargorust-clippy

How do I fix Clippy's needless_range_loop for loops that copy between slices with an offset?


When running cargo clippy, it complains about code like this:

pub fn from_bytes(data: [u8; 72]) -> Stuff {
    let mut ts = [0u8; 8];
    let mut cs = [0u8; 64];

    for b in 0..8 {
        ts[b] = data[b];
    }

    for bb in 0..64 {
        cs[bb] = data[bb + 8];
    }
}

with

warning: the loop variable `bb` is used to index `cs`
  --> src/main.rs:9:5
   |
9  | /     for bb in 0..64 {
10 | |         cs[bb] = data[bb + 8];
11 | |     }
   | |_____^
   |
   = note: #[warn(needless_range_loop)] on by default
   = help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#needless_range_loop
help: consider using an iterator
   |     for (bb, <item>) in cs.iter().enumerate().take(64) {

I can not wrap my head around this information. How can I change to the suggested method? I don't get how something like

for (bb, <item>) in cs.iter().enumerate().take(64)

can be applied to my use case.


Solution

  • Use clone_from_slice

    ts.clone_from_slice(&data[..8]);
    cs.clone_from_slice(&data[8..]);