Array Chunks Exact Splits Without Remainder

Iterate fixed-size batches with slice::chunks_exact, which skips the final short chunk, and recover the leftover through take_remainder.

RustData Integrity

Code

rustsnippet
22 lines
fn main() {
    let readings = [10, 21, 32, 43, 54, 65, 76];

    // chunks_exact:每批恰好 3 个;不足一批的尾部整块跳过
    let batches: Vec<&[i32]> = readings.chunks_exact(3).collect();
    println!("batches: {batches:?}");

    // 余数单独取回:Option<&[i32]>,整除时为 None
    let remainder = readings.chunks_exact(3).take_remainder();
    println!("remainder: {remainder:?}");

    // 批内求和:批与批互不重叠,适合分帧解析
    let totals: Vec<i32> = readings
        .chunks_exact(2)
        .map(|pair| pair.iter().sum())
        .collect();
    println!("pair sums: {totals:?}");

    // 对照 chunks:普通 chunks 会把尾巴作为一个不满批返回
    let sloppy: Vec<&[i32]> = readings.chunks(4).collect();
    println!("plain chunks: {sloppy:?}");
}

How it works

Array Chunks Exact Splits Without Remainder comes down to the function main.

Watch out for

  • The package manager never enters the picture for this snippet.

Using it

The main signature reads fn main()

The demo output is labeled (batches:, remainder:, pair sums:), so every printed line maps back to its originating operation.

Key statements worth quoting

.map(|pair| pair.iter().sum())
.collect();
let batches: Vec<&[i32]> = readings.chunks_exact(3).collect();
let sloppy: Vec<&[i32]> = readings.chunks(4).collect();

Interactive Tools for This Topic

FAQ

What does Array Chunks Exact Splits Without Remainder print when run?
The script runs standalone; its 4 labeled outputs include `batches:`, `remainder:`, `pair sums:`.