- take
Take the first N elements of an iterator
- 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.
examples/iterators/iterator-take/src/main.rs
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]