liveBook · Manning

Iterator method

As explained in Learn Rust in a Month of Lunches

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

An iterator gives you items one at a time, like drawing cards from a deck. Call `.iter()` on a vector when you want an iterator of references: you can read its items without taking the values out of the vector. section 8.2

Choose the method that matches what you need to do with each item:

  • `.iter()` gives references for reading items while keeping the original vector. section 8.2
  • `.iter_mut()` gives mutable references for changing items; `.into_iter()` gives values instead of references. section 8.2

Make a new vector without using up the old one

`let numbers = vec![1, 2, 3];` `let increased = numbers.iter().map(|x| x + 1).collect::<Vec<i32>>();` `increased` is `[2, 3, 4]`, and `numbers` is still available. Here `.map()` prepares a change for each item; `.collect()` makes the new vector. section 8.2 section 8.3.2

fn main() {
    let my_vec = vec!['a', 'b', '거', '柳'];          #1
 
    let mut my_vec_iter = my_vec.iter();             #2
 
    assert_eq!(my_vec_iter.next(), Some(&'a'));      #3
    assert_eq!(my_vec_iter.next(), Some(&'b'));
    assert_eq!(my_vec_iter.next(), Some(&'거'));
    assert_eq!(my_vec_iter.next(), Some(&'柳'));
    assert_eq!(my_vec_iter.next(), None);            #4
    assert_eq!(my_vec_iter.next(), None);            #5
}

Follow successive `.next()` calls: each item arrives as a reference inside `Some`, and the exhausted iterator returns `None`. section 8.2

Calling `.map()` after `.iter()` does not run the changes immediately. The iterator waits until something uses it, such as `.collect()`. If a mapped iterator is left unused, the compiler warns you. section 8.3.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Works through reference iteration, `.next()`, and lazy `.map()` chains, but defers a fuller explanation of closures.
Examples
Shows vector traversal, a transformed vector, successive `.next()` results, and a compiler warning for an unused iterator.
What it assumes
Introduces iterators through `for` loops and explains references versus values while leaving closures for later.
What you can do after
Apply it via Rust’s `.iter()` to read vector items without consuming the original or to collect transformed items into a new vector.
How it connects
Connects `.iter()` to references, `for` loops, `.next()`, `.map()`, and `.collect()`.

Also explained in

Compare how 2 books explain iterator method →

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.