首页 > 解决方案 > 如何迭代 itertools::chunks

问题描述

我是一个新的 rustacean,所以我的代码质量值得怀疑。在尝试获取生锈的绳索时,我遇到了以下问题。

我有一个位向量(bools),然后我想将其转换为字节向量(u8

我的第一个实现看起来像这样

let mut res: Vec<u8> = vec![];
let mut curr = 0;
for (idx, &bit) in bits.iter().enumerate() {
    let x = (idx % 8) as u8;
    if idx % 8 != 0 || idx == 0 {
        curr = set_bit_at(curr, (7 - (idx % 8)) as u32, bit).unwrap();
    } else {
        res.push(curr);
        curr = 0
    }
}
res.push(curr);

它有效,但感觉很丑陋,所以我尝试使用 crate itertools 来实现它。

let res = bits.iter()
    .chunks(8)
    .map(|split_byte: Vec<u8>| {
        split_byte.fold(0, |res, &bit| (res << 1) | (bit as u8))
    })
    .collect();

它确实看起来更好,但遗憾的是 - 它没有工作。

即使它chunks的返回类型似乎是一个迭代器,这一行也产生了以下错误

error[E0599]: no method named `map` found for type `bits::itertools::IntoChunks<std::slice::Iter<'_, bool>>` in the current scope

谁能告诉我做错了什么?

标签: rust

解决方案


我相信你误读了这里的文档。适合您的部分就在这里。你会在哪里看到(强调我的):

返回一个可以分块迭代器的迭代器

IntoChunks 基于 GroupBy:它是可迭代的(实现 IntoIterator,而不是 Iterator),并且仅在多个块迭代器同时处于活动状态时才进行缓冲。

因此,您需要into_itermap.


推荐阅读