Slice Chunks For Batch Processing
Batch a slice into fixed-size windows with chunks, keeping the short tail visible through chunks_exact's remainder.
Code
fn main() {
let readings = [4, 9, 15, 22, 7, 30, 11, 2, 18];
// chunks:把切片切成定长批次(batch),最后一批可能不满
for (i, batch) in readings.chunks(4).enumerate() {
let sum: i32 = batch.iter().sum();
println!("batch {}: {:?} sum {}", i, batch, sum);
}
// chunks_exact:只保留完整批次,余量用 remainder 单独取
let mut processed = 0;
for batch in readings.chunks_exact(4) {
processed += batch.len();
}
println!("processed in full batches: {}", processed);
println!("remainder: {:?}", readings.chunks_exact(4).remainder());
}How the snippet works
Slice Chunks For Batch Processing comes down to the function main.
Repetition is confined to for (i, batch) in readings.chunks(4).enumerate() — the rest of the file is straight-line.
Using it
The demo output is labeled (batch, processed in full batches:, remainder:); each label names the call that printed it.
Key statements
let sum: i32 = batch.iter().sum();
processed += batch.len();
Interactive Tools for This Topic
FAQ
- What does Slice Chunks For Batch Processing print when run?
- The script runs standalone; its 3 labeled outputs include `batch`, `processed in full batches:`, `remainder:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.