typestar

iter, iter_mut, into_iter in Rust

Three ways to walk a collection: by reference, by mutable reference, by value.

fn main() {
    let mut scores = vec![10, 20, 30];

    for s in scores.iter() {
        print!("{s} ");
    }
    println!();

    for s in scores.iter_mut() {
        *s *= 2;
    }
    println!("{:?}", scores);

    let owned: Vec<String> = vec!["a".to_string(), "b".to_string()];
    let joined: String = owned.into_iter().collect();
    println!("{joined}");
}

How it works

  1. iter yields &T and leaves the collection intact.
  2. iter_mut yields &mut T so you can edit in place.
  3. into_iter consumes the collection and yields owned values.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
309
Tokens
114
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 72 seconds.

Type this snippet

Step 3 of 3 in Borrowing, step 6 of 15 in Ownership & borrowing.

← Previous Next →