liveBook · Manning

Next

As explained in Learn Rust in a Month of Lunches

next is the iterator method that advances iteration and returns an Option containing the next item or indicating that iteration has ended.

next is the core iterator method in Rust. Each call advances the iterator and returns an Option: Some(item) while an item remains, then None when iteration has ended. section 8.2 section 8.4

Iterators are lazy, so creating one does not consume its items. Calling next manually gives direct control; for loops repeatedly call it until None, while methods such as collect can drive the iteration. section 8.2 section 8.4

Checking each item

let mut letters = vec!['a', 'b', '거', '柳'].iter(); assert_eq!(letters.next(), Some(&'a')); assert_eq!(letters.next(), Some(&'b')); assert_eq!(letters.next(), Some(&'거')); assert_eq!(letters.next(), Some(&'柳')); assert_eq!(letters.next(), None); assert_eq!(letters.next(), None); section 8.2

Implementing Iterator for a custom type requires next to:

  • Update the iterator's internal state. section 8.2
  • Return Some(value) when another item is available. section 8.2
  • Return None when iteration has finished; specialized iterators may deliberately behave differently. section 8.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
}

Trace successive next calls from the first item through the terminal None result. section 8.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains repeated calls, Some and None results, laziness, and custom implementations without detailing iterator internals beyond state updates.
Examples
Uses a character vector, assertions, for loops, and custom iterators that alternate, repeat indefinitely, or yield library books.
What you can do after
Operate iterators manually, interpret Option results, and implement next for custom Iterator types.
How it connects
Connects next with Iterator, Option, for loops, collect, iter, into_iter, and iter_mut.

Also explained in

Compare how 5 books explain next →

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.