iter_mut()
The .iter_mut() method borrows a slice or collection mutably (&mut self) and returns an iterator yielding exclusive mutable references (&mut T) to each element, allowing in-place modification without reallocating the collection.
Signature and Item Type
On a slice [T] (and on Vec<T> via deref coercion), .iter_mut() has the signature:
pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, T>
// where IterMut<'a, T>: Iterator<Item = &'a mut T>
Each &mut T yielded by IterMut points to a distinct element in the collection, so modifying elements in place is guaranteed not to alias any other element:
fn main() {
let mut prices = vec![100, 250, 400];
// Mutate each element in place by dereferencing `price: &mut i32`:
for price in prices.iter_mut() {
*price += 25;
}
println!("Updated prices: {prices:?}");
}
Updated prices: [125, 275, 425]
Equivalence of collection.iter_mut() and for x in &mut collection
Standard mutable collections implement IntoIterator for &mut Collection by delegating to .iter_mut():
for item in &mut collection { /* item: &mut T */ }
for item in collection.iter_mut() { /* item: &mut T */ }
Selective In-Place Mutation with .iter_mut().filter(...)
Chaining .iter_mut() with .filter(...) or .enumerate() lets you selectively modify elements in place without rebuilding the collection:
fn main() {
let mut ports = [80_u16, 443, 80, 8080, 80];
// Replace every port `80` with `8443` in place:
ports
.iter_mut()
.filter(|port| **port == 80)
.for_each(|port| *port = 8443);
println!("Updated ports: {ports:?}");
}
Updated ports: [8443, 443, 8443, 8080, 8443]
Collections That Do Not Provide iter_mut() on Keys
Ordered and hashed sets (HashSet<T>, BTreeSet<T>) and the keys of maps (HashMap<K, V>, BTreeMap<K, V>) do not provide iter_mut() over set elements or map keys, because mutating an element or key in place could change its hash or sort order and corrupt the collection's internal invariants. For HashMap<K, V> and BTreeMap<K, V>, .iter_mut() yields (&K, &mut V)—providing shared access to the key and mutable access only to the value:
use std::collections::BTreeMap;
fn main() {
let mut quotas = BTreeMap::from([("free", 100), ("pro", 1_000)]);
// Yields `(key: &&str, val: &mut i32)`:
for (_tier, limit) in quotas.iter_mut() {
*limit *= 2;
}
println!("Doubled quotas: {quotas:?}");
}
Doubled quotas: {"free": 200, "pro": 2000}