实现说明
Read::bytes 迭代器的 Result 项的核心是函数 main。
驱动整个流程的是 for item in cursor.by_ref().bytes() 这一个循环。match 把每种情况写明白;漏写一个就编译不过。
使用要点
- 跑完文件,输出里会留下标记——
read failed:、bytes:、again:。
常见问题
运行「Read::bytes 迭代器的 Result 项」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 read failed:、bytes:、again: 这类标签。
核心语句
let again = cursor.bytes().map(|b| b.unwrap_or(b'?')).collect::<Vec<_>>();
match item {
Ok(b) => bytes.push(b),
Err(e) => println!("read failed: {e}"),
}
代码示例
use std::io::{Cursor, Read};
fn main() {
// 含高位字节的字节流,模拟从网络分块读到的原始字节
let payload: Vec<u8> = vec![0x68, 0xC3, 0xA9, 0xFF, 0x21];
let mut cursor = Cursor::new(payload);
// Read::bytes:每项都是 io::Result<u8>,读错误在循环里处理而不中断整个流
let mut bytes = Vec::new();
for item in cursor.by_ref().bytes() {
match item {
Ok(b) => bytes.push(b),
Err(e) => println!("read failed: {e}"),
}
}
println!("bytes: {bytes:?}");
// Cursor 支持 set_position:回到开头重新读一遍
cursor.set_position(0);
let again = cursor.bytes().map(|b| b.unwrap_or(b'?')).collect::<Vec<_>>();
println!("again: {again:?}");
}