gpt4 book ai didi

io - 你如何将迭代器写入文件或标准输出(任何实现写入的东西)?

转载 作者:行者123 更新时间:2023-11-29 08:33:22 26 4
gpt4 key购买 nike

我有一个充满 u8 的迭代器是我想写入文件或标准输出。打电话io::stdout().write_all(foo)在我的迭代器上给我一个预期的类型 &[u8] ,并且我有一个迭代器类型。我明白为什么这不起作用。

我不明白的是如何更改它以使其正常工作。起初我尝试添加一个 .collect()到我的迭代器的末尾,但它说 the trait bound &[u8]: std::iter::FromIterator<u8> is not satisfieda collection of type &[u8] cannot be built from an iterator over elements of type u8 .

我觉得奇怪的是,当 Read 提供 bytes() 时,Write 不提供使用迭代器进行写入的方式。返回迭代器的函数。执行此操作的惯用方法是什么?

这是我的主要功能的内容:

io::stdout().write_all(
io::stdin().bytes().map(
|x| match x {
Ok(b) => b,
_ => panic!("There was an error reading from stdin"),
}
).repeat(3).collect()
);

最佳答案

It seems odd to me that Write doesn't provide a way of writing with an iterator, when Read provides a bytes() function that returns an iterator. What is the idiomatic way to do this?

确实感觉不一致,但您当然可以自己编写等价物。

类似于:

fn write_all<W: Write, I: Iterator<Item=u8>>(writer: &mut W, iter: I) {
const SIZE: usize = 1024;

let mut buffer = [0u8; SIZE];
let mut index = 0;

for i in iter {
buffer[index] = i;

index += 1;
if index == SIZE {
writer.write_all(&buffer);
}
}

writer.write_all(&buffer[..index]);
}

可能有一些方法可以让它更加地道,我还没有测试边界条件,但希望它能让你继续。

关于io - 你如何将迭代器写入文件或标准输出(任何实现写入的东西)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41653701/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com