5

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
jan
  • 211
  • 1
  • 7
  • 2
    I would consider the warning a false-positive for your usage – you're not just looping over the range of `0..len` of some collection just to index into it, you're looping over the range of `0..N` so that you can index into two different collections. That said, you should probably just use [`copy_from_slice`](https://doc.rust-lang.org/std/primitive.slice.html#method.copy_from_slice) here. – ildjarn Jun 15 '17 at 10:18

1 Answers1

6

Use clone_from_slice

ts.clone_from_slice(&data[..8]);
cs.clone_from_slice(&data[8..]);
Boiethios
  • 38,438
  • 19
  • 134
  • 183
  • 3
    And [reported](https://github.com/Manishearth/rust-clippy/issues/1831). It's true that this lint has some known problems. – mcarton Jun 15 '17 at 20:36