Iterator Advance By And Nth Skips

advance_by and nth(n) move an iterator forward by a position count without allocating anything for the items they skip.

RustData Integrity

Code

rustsnippet
21 lines
fn main() {
    let letters = ['a', 'b', 'c', 'd', 'e', 'f'];

    // Iterator::advance_by skips positions without binding the skipped items
    let mut skip_two = letters.iter();
    skip_two.advance_by(2).unwrap();
    println!("after advance_by(2): {:?}", skip_two.next());

    // nth(n) consumes n items and returns the one that lands next
    let mut by_nth = letters.iter();
    println!("nth(3): {:?}", by_nth.nth(3));
    println!("then next(): {:?}", by_nth.next());

    // past the end, advance_by reports the shortfall instead of panicking
    let mut exhausted = letters.iter();
    let shortfall = match exhausted.advance_by(10) {
        Ok(()) => 0,
        Err(k) => k.get(),
    };
    println!("advance_by(10) shortfall: {shortfall}, next: {:?}", exhausted.next());
}

What the code does

Iterator Advance By And Nth Skips comes down to the function main.

Pattern matching via match forces each shape of the value to be handled.

Caveats

  • All behavior comes from the standard library; nothing is external.

Using it

The primary signature, spelled out, is fn main()

Look for the after advance_by(2):, nth(3):, then next(): prefixes during the file’s run; they match each line of output to the step that emitted it.

Key statements

let shortfall = match exhausted.advance_by(10) {
    Ok(()) => 0,
    Err(k) => k.get(),
};
let mut exhausted = letters.iter();
let mut skip_two = letters.iter();

Interactive Tools for This Topic

FAQ

What does Iterator Advance By And Nth Skips print when run?
No setup needed: run the file and look for labeled lines like `after advance_by(2):`, `nth(3):`, `then next():` in the output.