实现说明
这份样例的核心结构围绕函数 main组织。
本示例的循环部分是 for (idx, block) in blocks.enumerate()。
使用要点
- 不涉及包管理器——每个调用都落在内建 API 上。
- 跑完文件,输出里会留下标记——
block、trailing remainder:、non-monotonic drops:。
常见问题
运行「用 chunks_exact 与 windows 处理切片分块」会打印什么?
运行文件本身,block、trailing remainder:、non-monotonic drops: 这些前缀各对应一段演示逻辑。
主要签名是 fn main()
核心语句
let checksum: u16 = block.iter().map(|&b| b as u16).sum();
.filter(|pair| pair[1] < pair[0])
.map(|pair| (pair[0], pair[1]))
.collect();
代码示例
fn main() {
let packet = [10_u8, 14, 19, 25, 30, 28, 35, 41, 99, 100];
// chunks_exact yields fixed 4-byte blocks and exposes trailing remainder
let blocks = packet.chunks_exact(4);
let tail = blocks.remainder();
for (idx, block) in blocks.enumerate() {
let checksum: u16 = block.iter().map(|&b| b as u16).sum();
println!("block {idx}: {block:?} checksum={checksum}");
}
println!("trailing remainder: {tail:?}");
// windows(2) checks adjacent monotonic steps across the stream
let drops: Vec<_> = packet
.windows(2)
.filter(|pair| pair[1] < pair[0])
.map(|pair| (pair[0], pair[1]))
.collect();
println!("non-monotonic drops: {drops:?}");
}