Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Take the first N elements of an iterator

  • take

  • take creates a new iterator from the first n element of any iterator.

  • It can be used on an infinite iterator as well.

  • The example we have here does not add value over just using a range, but for every other iterator it will make sense.

fn main() {
    let n = 5;
    let taken = (0..).take(n).collect::<Vec<_>>();
    let range = (0..n).collect::<Vec<_>>();
    assert_eq!(taken, range);
    println!("{:?}", taken);

    // If there are not enough iterations it stops when the iterator is exhausted
    let numbers = range.iter().take(10).collect::<Vec<_>>();
    println!("{:?}", numbers);
}
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]