rust - 如何迭代 itertools::chunks

标签 rust

我是一个新的 rust 菌,所以我的代码质量有问题。 在尝试获取 rust 的绳索时,我遇到了以下问题。

我有一个位向量 (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 的返回类型 seems作为一个迭代器,这一行产生了以下错误

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

谁能告诉我做错了什么?

最佳答案

我相信您误读了此处的文档。适合您的部分是 here .你会在哪里看到(强调我的):

Return an iterable that can chunk the iterator.

IntoChunks is based on GroupBy: it is iterable (implements IntoIterator, not Iterator), and it only buffers if several chunk iterators are alive at the same time.

因此,您需要在 map 之前使用 into_iter

关于rust - 如何迭代 itertools::chunks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56064633/

相关文章:

generics - 为什么移动闭包不会捕获具有通用类型的值?

rust - 自动使用 from_error 的 map_err 等价物

rust - 将 TaskManager 脚本从 gdscript/Godot 迁移到 bevy 和 rust

rust - 类型之间的 + 操作数是什么意思?

rust - 在 rust 中处理具有各种表示形式的枚举的规范方法

rust - 如何从对象安全特征对象中移出一个值?

rust - 如何从原始指针获取数组或切片?

rust - 如何将 yaml-rust 枚举存储到结构的实例中?

rust - 使用no_std进行的 cargo 测试失败,错误代码为176、160

input - 如何在 Rust 1.0 中读取用户输入的整数?