chunks_exact Batches Fixed Arrays

Process fixed arrays in constant-size groups with chunks_exact, upgrading each chunk to a &[T; N] view with try_into so fixed-size batch logic stays compile-che

RustData Integrity

Code

rustsnippet
29 lines
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);
}

How it works

The code’s whole job belongs to the functions checksum and main.

The file repeats itself only inside for chunk in frames.chunks_exact(3).

What to watch for

  • Everything it calls is documented as part of the language core.

Using it

Entry signature: fn checksum(triplet: &[u8; 3]) -> u32

Look for the chunk, each_ref:, chunks keeps the tail: prefixes when the file runs; they tie each line to its step.

Running the file executes main, which drives checksum in order.

The key statements, annotated

triplet.iter().map(|&b| b as u32).sum()
}
let triplet: &[u8; 3] = chunk.try_into().unwrap();
let tail: Vec<&[u8]> = ragged.chunks(2).collect();

Interactive Tools for This Topic

FAQ

What does chunks_exact Batches Fixed Arrays print when run?
No setup needed: run the file and look for labeled lines like `chunk`, `each_ref:`, `chunks keeps the tail:` in the output.