liveBook · Manning

Iter_mut

As explained in Learn Rust in a Month of Lunches

iter_mut is a Rust collection method that returns an iterator yielding mutable references to the collection's items.

iter_mut returns an iterator of mutable references, letting you change collection items directly. In a loop, each item is accessed through a mutable reference, so *item updates the value. section 8.2

Updating every vector item

Given let mut vector2 = vec![10, 20, 30];, vector2.iter_mut().for_each(|x| *x += 100); changes the vector to [110, 120, 130]. The mut binding permits modification, and *x accesses the referenced value. section 8.2

fn main() {
    let vector1 = vec![1, 2, 3];
    let mut vector2 = vec![10, 20, 30];
 
    for num in vector1.iter() {                   #1
        println!("Printing a &i32: {num}");
    }
    for num in vector1 {                          #2
        println!("Printing an i32: {num}");
    }
    for num in vector2.iter_mut() {               #3
        *num *= 10;
        println!("num is now {num}");
    }
    println!("{vector2:?}");
    // println!("{vector1:?}");                   #4
}

Compare iter_mut with iter and value iteration in one runnable example; the output shows mutable updates producing [100, 200, 300]. section 8.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines mutable-reference iteration, demonstrates dereferencing, and contrasts it with reference and value iteration.
Examples
Uses integer vectors, multiplication in a loop, and for_each with an incrementing closure.
What it assumes
Assumes basic vectors and for loops while defining iterators and mutable references with simple examples.
What you can do after
Apply it via Rust loops or for_each closures to modify every item in a mutable collection.
How it connects
Connects mutable references with iterators, for loops, closures, map, for_each, and collect.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.