iterator - 我如何修复 Clippy 的 needless_range_loop for loops that copy between slices with offset?

标签 iterator rust rust-cargo rust-clippy

当运行 cargo clippy 时,它会提示这样的代码:

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];
    }
}

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) {

我无法理解这个 information .如何更改为建议的方法?我不明白是怎么回事

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

可以应用于我的用例。

最佳答案

使用clone_from_slice

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

关于iterator - 我如何修复 Clippy 的 needless_range_loop for loops that copy between slices with offset?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44564772/

相关文章:

cmake - Rust中的Dockerfile错误,x86_64-unknown-linux-musl

c++ - vector 中的无效迭代器

c++ - 获取 std::string 容器的 C 字符串迭代器

rust - 虽然 let chain 导致 rust-analyzer 提示 Rust 1.66 中的功能不稳定,但这不是最近才合并到稳定版中的吗?

rust - 仅用于借用检查的零宽度引用?

rust - 带有多个二进制文件的死代码警告?

C++ 双向迭代器前缀递增

c++ - 双向链表后向指针

rust - 如何将枚举变体用作通用类型?

linux - 我应该在 Rust 中的什么地方保存我的配置文件