Mutate Windows With chunks_mut
Edit a Vec in fixed size batches through chunks_mut, then use chunks_exact_mut and remainder to handle the short trailing batch separately.
Code
fn main() {
let mut samples: Vec<i32> = (1..=12).collect();
// chunks_mut:按固定大小分批,直接改原 Vec,不额外收集
for batch in samples.chunks_mut(4) {
for value in batch.iter_mut() {
*value *= 10;
}
println!("batch {:?}", batch);
}
println!("after: {:?}", samples);
// chunks_exact_mut 只给整批,短尾留给 remainder
let mut tail = [1u8, 2, 3, 4, 5];
for window in tail.chunks_exact_mut(2) {
window.reverse();
}
println!("tail after swap: {:?}", tail);
println!("remainder: {:?}", tail.chunks_exact(2).remainder());
// 批大小必须大于 0,否则 panic
let size = 3;
for count in samples.chunks(size).map(<[i32]>::len) {
print!("{count} ");
}
println!();
}How it works
Mutate Windows With chunks_mut is built around the function main.
A single loop drives the file — for batch in samples.chunks_mut(4).
Caveats
- No external surface: all behavior comes from the standard library.
Putting it to use
Entry signature: fn main()
Each batch line prints one 4-element window as its values are multiplied by 10, after: shows the whole Vec mutated in place, and tail after swap: pairs with remainder: to separate the reversed 2-element windows from the odd element they leave alone.
Core lines
for count in samples.chunks(size).map(<[i32]>::len) {
print!("{count} ");
}
let mut samples: Vec<i32> = (1..=12).collect();
Interactive Tools for This Topic
FAQ
- What does Mutate Windows With chunks_mut print when run?
- Invoke the file as-is — the `batch`, `after:`, `tail after swap:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.