Skip to content

slice::iter_mut

slice methods · Collections

Level: reference · for working programmers

One line: An iterator over &mut T — edit every element in place.

pub fn iter_mut(&mut self) -> IterMut<'_, T>

Stable since 1.0.0. Its const form is still unstable.

for x in v.iter_mut() { *x *= 10; } — or for x in &mut v, which is the same call. The items are &mut T, so every write goes through a *; forgetting it is error[E0368] or E0308, depending on the operator, and the compiler names the fix.

While the iterator lives the slice is exclusively borrowed: no v.len(), no v[0] in the loop body. Index-and-value is iter_mut().enumerate(), and it is the usual way out of that corner — the index arrives with the element instead of being looked up.

It cannot add or remove elements, only change them. That is Vec::retain and friends, which own the length.

Example

slice_iter_mut.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let mut v = vec![1, 2, 3];
    for x in v.iter_mut() {
        *x *= 10;
    }
    println!("{v:?}");

    // `for x in &mut v` is the same call.
    for x in &mut v {
        *x += 1;
    }
    println!("{v:?}");

    // The items are &mut T: every write goes through a *.
    v.iter_mut().for_each(|x| *x = -*x);
    println!("{v:?}");

    // Index and element together, without indexing the borrowed Vec.
    for (i, x) in v.iter_mut().enumerate() {
        *x = i as i32 * 100;
    }
    println!("{v:?}");

    // Strings edit in place too: the &mut String is the item.
    let mut words = vec![String::from("a"), String::from("b")];
    for w in &mut words {
        w.push('!');
    }
    println!("{words:?}");
}

Verified output of slice_iter_mut.rs — regenerated by tools/run_examples.py, never hand-typed.

[10, 20, 30]
[11, 21, 31]
[-11, -21, -31]
[0, 100, 200]
["a!", "b!"]

See also

slice::iter_mut in the standard library ↗