实现说明
逻辑集中在函数 checksum、main里。
for chunk in frames.chunks_exact(3) 反复执行,循环体之外没有别的重复。
使用要点
- 每一步打印都带着自己的标签:
chunk、each_ref:、chunks keeps the tail:。 main按顺序串起checksum;运行文件就会把这个流程跑一遍。
常见问题
运行「chunks_exact 定长分批」会打印什么?
运行文件本身,chunk、each_ref:、chunks keeps the tail: 这些前缀各对应一段演示逻辑。
入口签名:fn checksum(triplet: &[u8; 3]) -> u32
核心语句
triplet.iter().map(|&b| b as u32).sum()
}
let triplet: &[u8; 3] = chunk.try_into().unwrap();
let tail: Vec<&[u8]> = ragged.chunks(2).collect();
代码示例
use std::convert::TryInto;
fn checksum(triplet: &[u8; 3]) -> u32 {
// 定长参数:编译器保证恰好 3 个元素,无需运行时检查
triplet.iter().map(|&b| b as u32).sum()
}
fn main() {
let frames = [10u8, 20, 30, 40, 50, 60];
// chunks_exact 按固定批长切分:批大小运行期传入,每个元素是 u8
for chunk in frames.chunks_exact(3) {
// 批长已知时 try_into 升格成 &[u8; 3],喂给定长参数的 checksum
let triplet: &[u8; 3] = chunk.try_into().unwrap();
println!("chunk {triplet:?} checksum {}", checksum(triplet));
}
// each_ref 把 [T; N] 变成 [&T; N]:无需拷贝就拿到逐元素引用数组
let refs: [&u8; 6] = frames.each_ref();
println!("each_ref: {:?}", refs);
// 对照 slice::chunks:同样的批长但保留不满批的尾巴
let ragged: [u8; 5] = [1, 2, 3, 4, 5];
let tail: Vec<&[u8]> = ragged.chunks(2).collect();
println!("chunks keeps the tail: {tail:?}");
// 6 能被 3 整除:chunks_exact 正好用尽全部元素,无 remainder
println!("array len divisible by 3: {}", frames.len() % 3 == 0);
}