rust - 如何迭代 itertools::chunks
问题描述
我是一个新的 rustacean,所以我的代码质量值得怀疑。在尝试获取生锈的绳索时,我遇到了以下问题。
我有一个位向量(bool
s),然后我想将其转换为字节向量(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
谁能告诉我做错了什么?
解决方案
我相信你误读了这里的文档。适合您的部分就在这里。你会在哪里看到(强调我的):
返回一个可以分块迭代器的迭代器。
IntoChunks 基于 GroupBy:它是可迭代的(实现 IntoIterator,而不是 Iterator),并且仅在多个块迭代器同时处于活动状态时才进行缓冲。
因此,您需要into_iter
在map
.
推荐阅读
- c++ - 如何仅在 OpenMP 上的线程上运行嵌套循环任务
- ruby-on-rails - 无法在生产中发送邮件 Net::OpenTimeout 错误(执行已过期)
- ruby-on-rails - rails_to 用于重复记录
- amazon-web-services - 在自我管理的 Kubernetes 上为 Istio 网关获取外部 IP
- postgresql - 安装 posgresql 时未定义的符号 dlsyn
- angular - 'ngx-avatar' 不是已知元素
- reference - Latex:在同一位置引用同名作者的两篇参考文献时如何避免省略作者姓名
- javascript - 我想将 JSON 数据从 json 文件调用到 html 表
- r - 在没有 NA 值的数据框中组合两列
- python-3.x - VSCode + Python 3.7.6 注解@pytest.mark.xfail undefined