Zip Two Mutable Iterators Update Pairs
zip() over two iter_mut() updates both collections in place; different collections give disjoint mutable borrows that coexist.
Code
fn main() {
let mut prices = [19_99, 4_50, 12_25];
let mut discounts = [2_00, 0_50, 1_25];
// two &mut iterators zip fine: different collections, disjoint borrows
for (price, discount) in prices.iter_mut().zip(discounts.iter_mut()) {
// update both sides pairwise
*price -= *discount;
*discount = 0;
}
println!("prices after discount: {:?}", prices);
println!("discounts applied: {:?}", discounts);
}How it works
All of the logic lives in the function main.
The loop for (price, discount) in prices.iter_mut().zip(discounts.iter_mut()) is the only repeated construct.
What to watch for
- Nothing arrives from a registry; the language ships every API used.
Using it
Signature: fn main()
The file announces its steps in the output: prices after discount:, discounts applied:.
Key statements worth quoting
for (price, discount) in prices.iter_mut().zip(discounts.iter_mut()) {
// update both sides pairwise
*price -= *discount;
*discount = 0;
}
Interactive Tools for This Topic
FAQ
- What does Zip Two Mutable Iterators Update Pairs print when run?
- Running the file directly is enough — expect labeled output lines such as `prices after discount:`, `discounts applied:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.