1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Composable external iteration.
13 //! If you've found yourself with a collection of some kind, and needed to
14 //! perform an operation on the elements of said collection, you'll quickly run
15 //! into 'iterators'. Iterators are heavily used in idiomatic Rust code, so
16 //! it's worth becoming familiar with them.
18 //! Before explaining more, let's talk about how this module is structured:
22 //! This module is largely organized by type:
24 //! * [Traits] are the core portion: these traits define what kind of iterators
25 //! exist and what you can do with them. The methods of these traits are worth
26 //! putting some extra study time into.
27 //! * [Functions] provide some helpful ways to create some basic iterators.
28 //! * [Structs] are often the return types of the various methods on this
29 //! module's traits. You'll usually want to look at the method that creates
30 //! the `struct`, rather than the `struct` itself. For more detail about why,
31 //! see '[Implementing Iterator](#implementing-iterator)'.
34 //! [Functions]: #functions
35 //! [Structs]: #structs
37 //! That's it! Let's dig into iterators.
41 //! The heart and soul of this module is the [`Iterator`] trait. The core of
42 //! [`Iterator`] looks like this:
47 //! fn next(&mut self) -> Option<Self::Item>;
51 //! An iterator has a method, [`next()`], which when called, returns an
52 //! [`Option`]`<Item>`. [`next()`] will return `Some(Item)` as long as there
53 //! are elements, and once they've all been exhausted, will return `None` to
54 //! indicate that iteration is finished. Individual iterators may choose to
55 //! resume iteration, and so calling [`next()`] again may or may not eventually
56 //! start returning `Some(Item)` again at some point.
58 //! [`Iterator`]'s full definition includes a number of other methods as well,
59 //! but they are default methods, built on top of [`next()`], and so you get
62 //! Iterators are also composable, and it's common to chain them together to do
63 //! more complex forms of processing. See the [Adapters](#adapters) section
64 //! below for more details.
66 //! [`Iterator`]: trait.Iterator.html
67 //! [`next()`]: trait.Iterator.html#tymethod.next
68 //! [`Option`]: ../../std/option/enum.Option.html
70 //! # The three forms of iteration
72 //! There are three common methods which can create iterators from a collection:
74 //! * `iter()`, which iterates over `&T`.
75 //! * `iter_mut()`, which iterates over `&mut T`.
76 //! * `into_iter()`, which iterates over `T`.
78 //! Various things in the standard library may implement one or more of the
79 //! three, where appropriate.
81 //! # Implementing Iterator
83 //! Creating an iterator of your own involves two steps: creating a `struct` to
84 //! hold the iterator's state, and then `impl`ementing [`Iterator`] for that
85 //! `struct`. This is why there are so many `struct`s in this module: there is
86 //! one for each iterator and iterator adapter.
88 //! Let's make an iterator named `Counter` which counts from `1` to `5`:
91 //! // First, the struct:
93 //! /// An iterator which counts from one to five
98 //! // we want our count to start at one, so let's add a new() method to help.
99 //! // This isn't strictly necessary, but is convenient. Note that we start
100 //! // `count` at zero, we'll see why in `next()`'s implementation below.
102 //! fn new() -> Counter {
103 //! Counter { count: 0 }
107 //! // Then, we implement `Iterator` for our `Counter`:
109 //! impl Iterator for Counter {
110 //! // we will be counting with usize
111 //! type Item = usize;
113 //! // next() is the only required method
114 //! fn next(&mut self) -> Option<usize> {
115 //! // increment our count. This is why we started at zero.
118 //! // check to see if we've finished counting or not.
119 //! if self.count < 6 {
127 //! // And now we can use it!
129 //! let mut counter = Counter::new();
131 //! let x = counter.next().unwrap();
132 //! println!("{}", x);
134 //! let x = counter.next().unwrap();
135 //! println!("{}", x);
137 //! let x = counter.next().unwrap();
138 //! println!("{}", x);
140 //! let x = counter.next().unwrap();
141 //! println!("{}", x);
143 //! let x = counter.next().unwrap();
144 //! println!("{}", x);
147 //! This will print `1` through `5`, each on their own line.
149 //! Calling `next()` this way gets repetitive. Rust has a construct which can
150 //! call `next()` on your iterator, until it reaches `None`. Let's go over that
153 //! # for Loops and IntoIterator
155 //! Rust's `for` loop syntax is actually sugar for iterators. Here's a basic
156 //! example of `for`:
159 //! let values = vec![1, 2, 3, 4, 5];
161 //! for x in values {
162 //! println!("{}", x);
166 //! This will print the numbers one through five, each on their own line. But
167 //! you'll notice something here: we never called anything on our vector to
168 //! produce an iterator. What gives?
170 //! There's a trait in the standard library for converting something into an
171 //! iterator: [`IntoIterator`]. This trait has one method, [`into_iter()`],
172 //! which converts the thing implementing [`IntoIterator`] into an iterator.
173 //! Let's take a look at that `for` loop again, and what the compiler converts
176 //! [`IntoIterator`]: trait.IntoIterator.html
177 //! [`into_iter()`]: trait.IntoIterator.html#tymethod.into_iter
180 //! let values = vec![1, 2, 3, 4, 5];
182 //! for x in values {
183 //! println!("{}", x);
187 //! Rust de-sugars this into:
190 //! let values = vec![1, 2, 3, 4, 5];
192 //! let result = match IntoIterator::into_iter(values) {
193 //! mut iter => loop {
194 //! match iter.next() {
195 //! Some(x) => { println!("{}", x); },
204 //! First, we call `into_iter()` on the value. Then, we match on the iterator
205 //! that returns, calling [`next()`] over and over until we see a `None`. At
206 //! that point, we `break` out of the loop, and we're done iterating.
208 //! There's one more subtle bit here: the standard library contains an
209 //! interesting implementation of [`IntoIterator`]:
212 //! impl<I: Iterator> IntoIterator for I
215 //! In other words, all [`Iterator`]s implement [`IntoIterator`], by just
216 //! returning themselves. This means two things:
218 //! 1. If you're writing an [`Iterator`], you can use it with a `for` loop.
219 //! 2. If you're creating a collection, implementing [`IntoIterator`] for it
220 //! will allow your collection to be used with the `for` loop.
224 //! Functions which take an [`Iterator`] and return another [`Iterator`] are
225 //! often called 'iterator adapters', as they're a form of the 'adapter
228 //! Common iterator adapters include [`map()`], [`take()`], and [`collect()`].
229 //! For more, see their documentation.
231 //! [`map()`]: trait.Iterator.html#method.map
232 //! [`take()`]: trait.Iterator.html#method.take
233 //! [`collect()`]: trait.Iterator.html#method.collect
237 //! Iterators (and iterator [adapters](#adapters)) are *lazy*. This means that
238 //! just creating an iterator doesn't _do_ a whole lot. Nothing really happens
239 //! until you call [`next()`]. This is sometimes a source of confusion when
240 //! creating an iterator solely for its side effects. For example, the [`map()`]
241 //! method calls a closure on each element it iterates over:
244 //! # #![allow(unused_must_use)]
245 //! let v = vec![1, 2, 3, 4, 5];
246 //! v.iter().map(|x| println!("{}", x));
249 //! This will not print any values, as we only created an iterator, rather than
250 //! using it. The compiler will warn us about this kind of behavior:
253 //! warning: unused result which must be used: iterator adaptors are lazy and
254 //! do nothing unless consumed
257 //! The idiomatic way to write a [`map()`] for its side effects is to use a
258 //! `for` loop instead:
261 //! let v = vec![1, 2, 3, 4, 5];
264 //! println!("{}", x);
268 //! [`map()`]: trait.Iterator.html#method.map
270 //! The two most common ways to evaluate an iterator are to use a `for` loop
271 //! like this, or using the [`collect()`] adapter to produce a new collection.
273 //! [`collect()`]: trait.Iterator.html#method.collect
277 //! Iterators do not have to be finite. As an example, an open-ended range is
278 //! an infinite iterator:
281 //! let numbers = 0..;
284 //! It is common to use the [`take()`] iterator adapter to turn an infinite
285 //! iterator into a finite one:
288 //! let numbers = 0..;
289 //! let five_numbers = numbers.take(5);
291 //! for number in five_numbers {
292 //! println!("{}", number);
296 //! This will print the numbers `0` through `4`, each on their own line.
298 //! [`take()`]: trait.Iterator.html#method.take
300 #![stable(feature = "rust1", since = "1.0.0")]
304 use cmp::{Ord, PartialOrd, PartialEq, Ordering};
305 use default::Default;
309 use num::{Zero, One};
310 use ops::{self, Add, Sub, FnMut, Mul};
311 use option::Option::{self, Some, None};
315 fn _assert_is_object_safe(_: &Iterator<Item=()>) {}
317 /// An interface for dealing with iterators.
319 /// This is the main iterator trait. For more about the concept of iterators
320 /// generally, please see the [module-level documentation]. In particular, you
321 /// may want to know how to [implement `Iterator`][impl].
323 /// [module-level documentation]: index.html
324 /// [impl]: index.html#implementing-iterator
325 #[stable(feature = "rust1", since = "1.0.0")]
326 #[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \
327 `.iter()` or a similar method"]
329 /// The type of the elements being iterated over.
330 #[stable(feature = "rust1", since = "1.0.0")]
333 /// Advances the iterator and returns the next value.
335 /// Returns `None` when iteration is finished. Individual iterator
336 /// implementations may choose to resume iteration, and so calling `next()`
337 /// again may or may not eventually start returning `Some(Item)` again at some
345 /// let a = [1, 2, 3];
347 /// let mut iter = a.iter();
349 /// // A call to next() returns the next value...
350 /// assert_eq!(Some(&1), iter.next());
351 /// assert_eq!(Some(&2), iter.next());
352 /// assert_eq!(Some(&3), iter.next());
354 /// // ... and then None once it's over.
355 /// assert_eq!(None, iter.next());
357 /// // More calls may or may not return None. Here, they always will.
358 /// assert_eq!(None, iter.next());
359 /// assert_eq!(None, iter.next());
361 #[stable(feature = "rust1", since = "1.0.0")]
362 fn next(&mut self) -> Option<Self::Item>;
364 /// Returns the bounds on the remaining length of the iterator.
366 /// Specifically, `size_hint()` returns a tuple where the first element
367 /// is the lower bound, and the second element is the upper bound.
369 /// The second half of the tuple that is returned is an `Option<usize>`. A
370 /// `None` here means that either there is no known upper bound, or the
371 /// upper bound is larger than `usize`.
373 /// # Implementation notes
375 /// It is not enforced that an iterator implementation yields the declared
376 /// number of elements. A buggy iterator may yield less than the lower bound
377 /// or more than the upper bound of elements.
379 /// `size_hint()` is primarily intended to be used for optimizations such as
380 /// reserving space for the elements of the iterator, but must not be
381 /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
382 /// implementation of `size_hint()` should not lead to memory safety
385 /// That said, the implementation should provide a correct estimation,
386 /// because otherwise it would be a violation of the trait's protocol.
388 /// The default implementation returns `(0, None)` which is correct for any
396 /// let a = [1, 2, 3];
397 /// let iter = a.iter();
399 /// assert_eq!((3, Some(3)), iter.size_hint());
402 /// A more complex example:
405 /// // The even numbers from zero to ten.
406 /// let iter = (0..10).filter(|x| x % 2 == 0);
408 /// // We might iterate from zero to ten times. Knowing that it's five
409 /// // exactly wouldn't be possible without executing filter().
410 /// assert_eq!((0, Some(10)), iter.size_hint());
412 /// // Let's add one five more numbers with chain()
413 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
415 /// // now both bounds are increased by five
416 /// assert_eq!((5, Some(15)), iter.size_hint());
419 /// Returning `None` for an upper bound:
422 /// // an infinite iterator has no upper bound
425 /// assert_eq!((0, None), iter.size_hint());
428 #[stable(feature = "rust1", since = "1.0.0")]
429 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
431 /// Consumes the iterator, counting the number of iterations and returning it.
433 /// This method will evaluate the iterator until its [`next()`] returns
434 /// `None`. Once `None` is encountered, `count()` returns the number of
435 /// times it called [`next()`].
437 /// [`next()`]: #tymethod.next
439 /// # Overflow Behavior
441 /// The method does no guarding against overflows, so counting elements of
442 /// an iterator with more than `usize::MAX` elements either produces the
443 /// wrong result or panics. If debug assertions are enabled, a panic is
448 /// This function might panic if the iterator has more than `usize::MAX`
456 /// let a = [1, 2, 3];
457 /// assert_eq!(a.iter().count(), 3);
459 /// let a = [1, 2, 3, 4, 5];
460 /// assert_eq!(a.iter().count(), 5);
463 #[stable(feature = "rust1", since = "1.0.0")]
464 fn count(self) -> usize where Self: Sized {
466 self.fold(0, |cnt, _| cnt + 1)
469 /// Consumes the iterator, returning the last element.
471 /// This method will evaluate the iterator until it returns `None`. While
472 /// doing so, it keeps track of the current element. After `None` is
473 /// returned, `last()` will then return the last element it saw.
480 /// let a = [1, 2, 3];
481 /// assert_eq!(a.iter().last(), Some(&3));
483 /// let a = [1, 2, 3, 4, 5];
484 /// assert_eq!(a.iter().last(), Some(&5));
487 #[stable(feature = "rust1", since = "1.0.0")]
488 fn last(self) -> Option<Self::Item> where Self: Sized {
490 for x in self { last = Some(x); }
494 /// Consumes the `n` first elements of the iterator, then returns the
497 /// This method will evaluate the iterator `n` times, discarding those elements.
498 /// After it does so, it will call [`next()`] and return its value.
500 /// [`next()`]: #tymethod.next
502 /// Like most indexing operations, the count starts from zero, so `nth(0)`
503 /// returns the first value, `nth(1)` the second, and so on.
505 /// `nth()` will return `None` if `n` is larger than the length of the
513 /// let a = [1, 2, 3];
514 /// assert_eq!(a.iter().nth(1), Some(&2));
517 /// Calling `nth()` multiple times doesn't rewind the iterator:
520 /// let a = [1, 2, 3];
522 /// let mut iter = a.iter();
524 /// assert_eq!(iter.nth(1), Some(&2));
525 /// assert_eq!(iter.nth(1), None);
528 /// Returning `None` if there are less than `n` elements:
531 /// let a = [1, 2, 3];
532 /// assert_eq!(a.iter().nth(10), None);
535 #[stable(feature = "rust1", since = "1.0.0")]
536 fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
538 if n == 0 { return Some(x) }
544 /// Takes two iterators and creates a new iterator over both in sequence.
546 /// `chain()` will return a new iterator which will first iterate over
547 /// values from the first iterator and then over values from the second
550 /// In other words, it links two iterators together, in a chain. 🔗
557 /// let a1 = [1, 2, 3];
558 /// let a2 = [4, 5, 6];
560 /// let mut iter = a1.iter().chain(a2.iter());
562 /// assert_eq!(iter.next(), Some(&1));
563 /// assert_eq!(iter.next(), Some(&2));
564 /// assert_eq!(iter.next(), Some(&3));
565 /// assert_eq!(iter.next(), Some(&4));
566 /// assert_eq!(iter.next(), Some(&5));
567 /// assert_eq!(iter.next(), Some(&6));
568 /// assert_eq!(iter.next(), None);
571 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
572 /// anything that can be converted into an [`Iterator`], not just an
573 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
574 /// [`IntoIterator`], and so can be passed to `chain()` directly:
576 /// [`IntoIterator`]: trait.IntoIterator.html
577 /// [`Iterator`]: trait.Iterator.html
580 /// let s1 = &[1, 2, 3];
581 /// let s2 = &[4, 5, 6];
583 /// let mut iter = s1.iter().chain(s2);
585 /// assert_eq!(iter.next(), Some(&1));
586 /// assert_eq!(iter.next(), Some(&2));
587 /// assert_eq!(iter.next(), Some(&3));
588 /// assert_eq!(iter.next(), Some(&4));
589 /// assert_eq!(iter.next(), Some(&5));
590 /// assert_eq!(iter.next(), Some(&6));
591 /// assert_eq!(iter.next(), None);
594 #[stable(feature = "rust1", since = "1.0.0")]
595 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
596 Self: Sized, U: IntoIterator<Item=Self::Item>,
598 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
601 /// 'Zips up' two iterators into a single iterator of pairs.
603 /// `zip()` returns a new iterator that will iterate over two other
604 /// iterators, returning a tuple where the first element comes from the
605 /// first iterator, and the second element comes from the second iterator.
607 /// In other words, it zips two iterators together, into a single one.
609 /// When either iterator returns `None`, all further calls to `next()`
610 /// will return `None`.
617 /// let a1 = [1, 2, 3];
618 /// let a2 = [4, 5, 6];
620 /// let mut iter = a1.iter().zip(a2.iter());
622 /// assert_eq!(iter.next(), Some((&1, &4)));
623 /// assert_eq!(iter.next(), Some((&2, &5)));
624 /// assert_eq!(iter.next(), Some((&3, &6)));
625 /// assert_eq!(iter.next(), None);
628 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
629 /// anything that can be converted into an [`Iterator`], not just an
630 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
631 /// [`IntoIterator`], and so can be passed to `zip()` directly:
633 /// [`IntoIterator`]: trait.IntoIterator.html
634 /// [`Iterator`]: trait.Iterator.html
637 /// let s1 = &[1, 2, 3];
638 /// let s2 = &[4, 5, 6];
640 /// let mut iter = s1.iter().zip(s2);
642 /// assert_eq!(iter.next(), Some((&1, &4)));
643 /// assert_eq!(iter.next(), Some((&2, &5)));
644 /// assert_eq!(iter.next(), Some((&3, &6)));
645 /// assert_eq!(iter.next(), None);
648 /// `zip()` is often used to zip an infinite iterator to a finite one.
649 /// This works because the finite iterator will eventually return `None`,
650 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]:
653 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
655 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
657 /// assert_eq!((0, 'f'), enumerate[0]);
658 /// assert_eq!((0, 'f'), zipper[0]);
660 /// assert_eq!((1, 'o'), enumerate[1]);
661 /// assert_eq!((1, 'o'), zipper[1]);
663 /// assert_eq!((2, 'o'), enumerate[2]);
664 /// assert_eq!((2, 'o'), zipper[2]);
667 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
669 #[stable(feature = "rust1", since = "1.0.0")]
670 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
671 Self: Sized, U: IntoIterator
673 Zip{a: self, b: other.into_iter()}
676 /// Takes a closure and creates an iterator which calls that closure on each
679 /// `map()` transforms one iterator into another, by means of its argument:
680 /// something that implements `FnMut`. It produces a new iterator which
681 /// calls this closure on each element of the original iterator.
683 /// If you are good at thinking in types, you can think of `map()` like this:
684 /// If you have an iterator that gives you elements of some type `A`, and
685 /// you want an iterator of some other type `B`, you can use `map()`,
686 /// passing a closure that takes an `A` and returns a `B`.
688 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
689 /// lazy, it is best used when you're already working with other iterators.
690 /// If you're doing some sort of looping for a side effect, it's considered
691 /// more idiomatic to use [`for`] than `map()`.
693 /// [`for`]: ../../book/loops.html#for
700 /// let a = [1, 2, 3];
702 /// let mut iter = a.into_iter().map(|x| 2 * x);
704 /// assert_eq!(iter.next(), Some(2));
705 /// assert_eq!(iter.next(), Some(4));
706 /// assert_eq!(iter.next(), Some(6));
707 /// assert_eq!(iter.next(), None);
710 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
713 /// # #![allow(unused_must_use)]
714 /// // don't do this:
715 /// (0..5).map(|x| println!("{}", x));
717 /// // it won't even execute, as it is lazy. Rust will warn you about this.
719 /// // Instead, use for:
721 /// println!("{}", x);
725 #[stable(feature = "rust1", since = "1.0.0")]
726 fn map<B, F>(self, f: F) -> Map<Self, F> where
727 Self: Sized, F: FnMut(Self::Item) -> B,
729 Map{iter: self, f: f}
732 /// Creates an iterator which uses a closure to determine if an element
733 /// should be yielded.
735 /// The closure must return `true` or `false`. `filter()` creates an
736 /// iterator which calls this closure on each element. If the closure
737 /// returns `true`, then the element is returned. If the closure returns
738 /// `false`, it will try again, and call the closure on the next element,
739 /// seeing if it passes the test.
746 /// let a = [0i32, 1, 2];
748 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
750 /// assert_eq!(iter.next(), Some(&1));
751 /// assert_eq!(iter.next(), Some(&2));
752 /// assert_eq!(iter.next(), None);
755 /// Because the closure passed to `filter()` takes a reference, and many
756 /// iterators iterate over references, this leads to a possibly confusing
757 /// situation, where the type of the closure is a double reference:
760 /// let a = [0, 1, 2];
762 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
764 /// assert_eq!(iter.next(), Some(&2));
765 /// assert_eq!(iter.next(), None);
768 /// It's common to instead use destructuring on the argument to strip away
772 /// let a = [0, 1, 2];
774 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
776 /// assert_eq!(iter.next(), Some(&2));
777 /// assert_eq!(iter.next(), None);
783 /// let a = [0, 1, 2];
785 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
787 /// assert_eq!(iter.next(), Some(&2));
788 /// assert_eq!(iter.next(), None);
793 #[stable(feature = "rust1", since = "1.0.0")]
794 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
795 Self: Sized, P: FnMut(&Self::Item) -> bool,
797 Filter{iter: self, predicate: predicate}
800 /// Creates an iterator that both filters and maps.
802 /// The closure must return an [`Option<T>`]. `filter_map()` creates an
803 /// iterator which calls this closure on each element. If the closure
804 /// returns `Some(element)`, then that element is returned. If the
805 /// closure returns `None`, it will try again, and call the closure on the
806 /// next element, seeing if it will return `Some`.
808 /// [`Option<T>`]: ../../std/option/enum.Option.html
810 /// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this
813 /// [`filter()`]: #method.filter
814 /// [`map()`]: #method.map
816 /// > If the closure returns `Some(element)`, then that element is returned.
818 /// In other words, it removes the [`Option<T>`] layer automatically. If your
819 /// mapping is already returning an [`Option<T>`] and you want to skip over
820 /// `None`s, then `filter_map()` is much, much nicer to use.
827 /// let a = ["1", "2", "lol"];
829 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
831 /// assert_eq!(iter.next(), Some(1));
832 /// assert_eq!(iter.next(), Some(2));
833 /// assert_eq!(iter.next(), None);
836 /// Here's the same example, but with [`filter()`] and [`map()`]:
839 /// let a = ["1", "2", "lol"];
841 /// let mut iter = a.iter()
842 /// .map(|s| s.parse().ok())
843 /// .filter(|s| s.is_some());
845 /// assert_eq!(iter.next(), Some(Some(1)));
846 /// assert_eq!(iter.next(), Some(Some(2)));
847 /// assert_eq!(iter.next(), None);
850 /// There's an extra layer of `Some` in there.
852 #[stable(feature = "rust1", since = "1.0.0")]
853 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
854 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
856 FilterMap { iter: self, f: f }
859 /// Creates an iterator which gives the current iteration count as well as
862 /// The iterator returned yields pairs `(i, val)`, where `i` is the
863 /// current index of iteration and `val` is the value returned by the
866 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
867 /// different sized integer, the [`zip()`] function provides similar
870 /// [`usize`]: ../../std/primitive.usize.html
871 /// [`zip()`]: #method.zip
873 /// # Overflow Behavior
875 /// The method does no guarding against overflows, so enumerating more than
876 /// [`usize::MAX`] elements either produces the wrong result or panics. If
877 /// debug assertions are enabled, a panic is guaranteed.
879 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
883 /// The returned iterator might panic if the to-be-returned index would
884 /// overflow a `usize`.
889 /// let a = [1, 2, 3];
891 /// let mut iter = a.iter().enumerate();
893 /// assert_eq!(iter.next(), Some((0, &1)));
894 /// assert_eq!(iter.next(), Some((1, &2)));
895 /// assert_eq!(iter.next(), Some((2, &3)));
896 /// assert_eq!(iter.next(), None);
899 #[stable(feature = "rust1", since = "1.0.0")]
900 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
901 Enumerate { iter: self, count: 0 }
904 /// Creates an iterator which can use `peek` to look at the next element of
905 /// the iterator without consuming it.
907 /// Adds a [`peek()`] method to an iterator. See its documentation for
908 /// more information.
910 /// Note that the underlying iterator is still advanced when `peek` is
911 /// called for the first time: In order to retrieve the next element,
912 /// `next` is called on the underlying iterator, hence any side effects of
913 /// the `next` method will occur.
915 /// [`peek()`]: struct.Peekable.html#method.peek
922 /// let xs = [1, 2, 3];
924 /// let mut iter = xs.iter().peekable();
926 /// // peek() lets us see into the future
927 /// assert_eq!(iter.peek(), Some(&&1));
928 /// assert_eq!(iter.next(), Some(&1));
930 /// assert_eq!(iter.next(), Some(&2));
932 /// // we can peek() multiple times, the iterator won't advance
933 /// assert_eq!(iter.peek(), Some(&&3));
934 /// assert_eq!(iter.peek(), Some(&&3));
936 /// assert_eq!(iter.next(), Some(&3));
938 /// // after the iterator is finished, so is peek()
939 /// assert_eq!(iter.peek(), None);
940 /// assert_eq!(iter.next(), None);
943 #[stable(feature = "rust1", since = "1.0.0")]
944 fn peekable(self) -> Peekable<Self> where Self: Sized {
945 Peekable{iter: self, peeked: None}
948 /// Creates an iterator that [`skip()`]s elements based on a predicate.
950 /// [`skip()`]: #method.skip
952 /// `skip_while()` takes a closure as an argument. It will call this
953 /// closure on each element of the iterator, and ignore elements
954 /// until it returns `false`.
956 /// After `false` is returned, `skip_while()`'s job is over, and the
957 /// rest of the elements are yielded.
964 /// let a = [-1i32, 0, 1];
966 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
968 /// assert_eq!(iter.next(), Some(&0));
969 /// assert_eq!(iter.next(), Some(&1));
970 /// assert_eq!(iter.next(), None);
973 /// Because the closure passed to `skip_while()` takes a reference, and many
974 /// iterators iterate over references, this leads to a possibly confusing
975 /// situation, where the type of the closure is a double reference:
978 /// let a = [-1, 0, 1];
980 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
982 /// assert_eq!(iter.next(), Some(&0));
983 /// assert_eq!(iter.next(), Some(&1));
984 /// assert_eq!(iter.next(), None);
987 /// Stopping after an initial `false`:
990 /// let a = [-1, 0, 1, -2];
992 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
994 /// assert_eq!(iter.next(), Some(&0));
995 /// assert_eq!(iter.next(), Some(&1));
997 /// // while this would have been false, since we already got a false,
998 /// // skip_while() isn't used any more
999 /// assert_eq!(iter.next(), Some(&-2));
1001 /// assert_eq!(iter.next(), None);
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
1006 Self: Sized, P: FnMut(&Self::Item) -> bool,
1008 SkipWhile{iter: self, flag: false, predicate: predicate}
1011 /// Creates an iterator that yields elements based on a predicate.
1013 /// `take_while()` takes a closure as an argument. It will call this
1014 /// closure on each element of the iterator, and yield elements
1015 /// while it returns `true`.
1017 /// After `false` is returned, `take_while()`'s job is over, and the
1018 /// rest of the elements are ignored.
1025 /// let a = [-1i32, 0, 1];
1027 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
1029 /// assert_eq!(iter.next(), Some(&-1));
1030 /// assert_eq!(iter.next(), None);
1033 /// Because the closure passed to `take_while()` takes a reference, and many
1034 /// iterators iterate over references, this leads to a possibly confusing
1035 /// situation, where the type of the closure is a double reference:
1038 /// let a = [-1, 0, 1];
1040 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
1042 /// assert_eq!(iter.next(), Some(&-1));
1043 /// assert_eq!(iter.next(), None);
1046 /// Stopping after an initial `false`:
1049 /// let a = [-1, 0, 1, -2];
1051 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
1053 /// assert_eq!(iter.next(), Some(&-1));
1055 /// // We have more elements that are less than zero, but since we already
1056 /// // got a false, take_while() isn't used any more
1057 /// assert_eq!(iter.next(), None);
1060 /// Because `take_while()` needs to look at the value in order to see if it
1061 /// should be included or not, consuming iterators will see that it is
1065 /// let a = [1, 2, 3, 4];
1066 /// let mut iter = a.into_iter();
1068 /// let result: Vec<i32> = iter.by_ref()
1069 /// .take_while(|n| **n != 3)
1073 /// assert_eq!(result, &[1, 2]);
1075 /// let result: Vec<i32> = iter.cloned().collect();
1077 /// assert_eq!(result, &[4]);
1080 /// The `3` is no longer there, because it was consumed in order to see if
1081 /// the iteration should stop, but wasn't placed back into the iterator or
1082 /// some similar thing.
1084 #[stable(feature = "rust1", since = "1.0.0")]
1085 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
1086 Self: Sized, P: FnMut(&Self::Item) -> bool,
1088 TakeWhile{iter: self, flag: false, predicate: predicate}
1091 /// Creates an iterator that skips the first `n` elements.
1093 /// After they have been consumed, the rest of the elements are yielded.
1100 /// let a = [1, 2, 3];
1102 /// let mut iter = a.iter().skip(2);
1104 /// assert_eq!(iter.next(), Some(&3));
1105 /// assert_eq!(iter.next(), None);
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
1110 Skip{iter: self, n: n}
1113 /// Creates an iterator that yields its first `n` elements.
1120 /// let a = [1, 2, 3];
1122 /// let mut iter = a.iter().take(2);
1124 /// assert_eq!(iter.next(), Some(&1));
1125 /// assert_eq!(iter.next(), Some(&2));
1126 /// assert_eq!(iter.next(), None);
1129 /// `take()` is often used with an infinite iterator, to make it finite:
1132 /// let mut iter = (0..).take(3);
1134 /// assert_eq!(iter.next(), Some(0));
1135 /// assert_eq!(iter.next(), Some(1));
1136 /// assert_eq!(iter.next(), Some(2));
1137 /// assert_eq!(iter.next(), None);
1140 #[stable(feature = "rust1", since = "1.0.0")]
1141 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
1142 Take{iter: self, n: n}
1145 /// An iterator adaptor similar to [`fold()`] that holds internal state and
1146 /// produces a new iterator.
1148 /// [`fold()`]: #method.fold
1150 /// `scan()` takes two arguments: an initial value which seeds the internal
1151 /// state, and a closure with two arguments, the first being a mutable
1152 /// reference to the internal state and the second an iterator element.
1153 /// The closure can assign to the internal state to share state between
1156 /// On iteration, the closure will be applied to each element of the
1157 /// iterator and the return value from the closure, an [`Option`], is
1158 /// yielded by the iterator.
1160 /// [`Option`]: ../../std/option/enum.Option.html
1167 /// let a = [1, 2, 3];
1169 /// let mut iter = a.iter().scan(1, |state, &x| {
1170 /// // each iteration, we'll multiply the state by the element
1171 /// *state = *state * x;
1173 /// // the value passed on to the next iteration
1177 /// assert_eq!(iter.next(), Some(1));
1178 /// assert_eq!(iter.next(), Some(2));
1179 /// assert_eq!(iter.next(), Some(6));
1180 /// assert_eq!(iter.next(), None);
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1185 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
1187 Scan{iter: self, f: f, state: initial_state}
1190 /// Creates an iterator that works like map, but flattens nested structure.
1192 /// The [`map()`] adapter is very useful, but only when the closure
1193 /// argument produces values. If it produces an iterator instead, there's
1194 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1197 /// [`map()`]: #method.map
1199 /// Another way of thinking about `flat_map()`: [`map()`]'s closure returns
1200 /// one item for each element, and `flat_map()`'s closure returns an
1201 /// iterator for each element.
1208 /// let words = ["alpha", "beta", "gamma"];
1210 /// // chars() returns an iterator
1211 /// let merged: String = words.iter()
1212 /// .flat_map(|s| s.chars())
1214 /// assert_eq!(merged, "alphabetagamma");
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1219 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
1221 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
1224 /// Creates an iterator which ends after the first `None`.
1226 /// After an iterator returns `None`, future calls may or may not yield
1227 /// `Some(T)` again. `fuse()` adapts an iterator, ensuring that after a
1228 /// `None` is given, it will always return `None` forever.
1235 /// // an iterator which alternates between Some and None
1236 /// struct Alternate {
1240 /// impl Iterator for Alternate {
1241 /// type Item = i32;
1243 /// fn next(&mut self) -> Option<i32> {
1244 /// let val = self.state;
1245 /// self.state = self.state + 1;
1247 /// // if it's even, Some(i32), else None
1248 /// if val % 2 == 0 {
1256 /// let mut iter = Alternate { state: 0 };
1258 /// // we can see our iterator going back and forth
1259 /// assert_eq!(iter.next(), Some(0));
1260 /// assert_eq!(iter.next(), None);
1261 /// assert_eq!(iter.next(), Some(2));
1262 /// assert_eq!(iter.next(), None);
1264 /// // however, once we fuse it...
1265 /// let mut iter = iter.fuse();
1267 /// assert_eq!(iter.next(), Some(4));
1268 /// assert_eq!(iter.next(), None);
1270 /// // it will always return None after the first time.
1271 /// assert_eq!(iter.next(), None);
1272 /// assert_eq!(iter.next(), None);
1273 /// assert_eq!(iter.next(), None);
1276 #[stable(feature = "rust1", since = "1.0.0")]
1277 fn fuse(self) -> Fuse<Self> where Self: Sized {
1278 Fuse{iter: self, done: false}
1281 /// Do something with each element of an iterator, passing the value on.
1283 /// When using iterators, you'll often chain several of them together.
1284 /// While working on such code, you might want to check out what's
1285 /// happening at various parts in the pipeline. To do that, insert
1286 /// a call to `inspect()`.
1288 /// It's much more common for `inspect()` to be used as a debugging tool
1289 /// than to exist in your final code, but never say never.
1296 /// let a = [1, 4, 2, 3];
1298 /// // this iterator sequence is complex.
1299 /// let sum = a.iter()
1301 /// .filter(|&x| x % 2 == 0)
1302 /// .fold(0, |sum, i| sum + i);
1304 /// println!("{}", sum);
1306 /// // let's add some inspect() calls to investigate what's happening
1307 /// let sum = a.iter()
1309 /// .inspect(|x| println!("about to filter: {}", x))
1310 /// .filter(|&x| x % 2 == 0)
1311 /// .inspect(|x| println!("made it through filter: {}", x))
1312 /// .fold(0, |sum, i| sum + i);
1314 /// println!("{}", sum);
1317 /// This will print:
1320 /// about to filter: 1
1321 /// about to filter: 4
1322 /// made it through filter: 4
1323 /// about to filter: 2
1324 /// made it through filter: 2
1325 /// about to filter: 3
1329 #[stable(feature = "rust1", since = "1.0.0")]
1330 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1331 Self: Sized, F: FnMut(&Self::Item),
1333 Inspect{iter: self, f: f}
1336 /// Borrows an iterator, rather than consuming it.
1338 /// This is useful to allow applying iterator adaptors while still
1339 /// retaining ownership of the original iterator.
1346 /// let a = [1, 2, 3];
1348 /// let iter = a.into_iter();
1350 /// let sum: i32 = iter.take(5)
1351 /// .fold(0, |acc, &i| acc + i );
1353 /// assert_eq!(sum, 6);
1355 /// // if we try to use iter again, it won't work. The following line
1356 /// // gives "error: use of moved value: `iter`
1357 /// // assert_eq!(iter.next(), None);
1359 /// // let's try that again
1360 /// let a = [1, 2, 3];
1362 /// let mut iter = a.into_iter();
1364 /// // instead, we add in a .by_ref()
1365 /// let sum: i32 = iter.by_ref()
1367 /// .fold(0, |acc, &i| acc + i );
1369 /// assert_eq!(sum, 3);
1371 /// // now this is just fine:
1372 /// assert_eq!(iter.next(), Some(&3));
1373 /// assert_eq!(iter.next(), None);
1375 #[stable(feature = "rust1", since = "1.0.0")]
1376 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1378 /// Transforms an iterator into a collection.
1380 /// `collect()` can take anything iterable, and turn it into a relevant
1381 /// collection. This is one of the more powerful methods in the standard
1382 /// library, used in a variety of contexts.
1384 /// The most basic pattern in which `collect()` is used is to turn one
1385 /// collection into another. You take a collection, call `iter()` on it,
1386 /// do a bunch of transformations, and then `collect()` at the end.
1388 /// One of the keys to `collect()`'s power is that many things you might
1389 /// not think of as 'collections' actually are. For example, a [`String`]
1390 /// is a collection of [`char`]s. And a collection of [`Result<T, E>`] can
1391 /// be thought of as single `Result<Collection<T>, E>`. See the examples
1394 /// [`String`]: ../../std/string/struct.String.html
1395 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
1396 /// [`char`]: ../../std/primitive.char.html
1398 /// Because `collect()` is so general, it can cause problems with type
1399 /// inference. As such, `collect()` is one of the few times you'll see
1400 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1401 /// helps the inference algorithm understand specifically which collection
1402 /// you're trying to collect into.
1409 /// let a = [1, 2, 3];
1411 /// let doubled: Vec<i32> = a.iter()
1412 /// .map(|&x| x * 2)
1415 /// assert_eq!(vec![2, 4, 6], doubled);
1418 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1419 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1421 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1424 /// use std::collections::VecDeque;
1426 /// let a = [1, 2, 3];
1428 /// let doubled: VecDeque<i32> = a.iter()
1429 /// .map(|&x| x * 2)
1432 /// assert_eq!(2, doubled[0]);
1433 /// assert_eq!(4, doubled[1]);
1434 /// assert_eq!(6, doubled[2]);
1437 /// Using the 'turbofish' instead of annotating `doubled`:
1440 /// let a = [1, 2, 3];
1442 /// let doubled = a.iter()
1443 /// .map(|&x| x * 2)
1444 /// .collect::<Vec<i32>>();
1446 /// assert_eq!(vec![2, 4, 6], doubled);
1449 /// Because `collect()` cares about what you're collecting into, you can
1450 /// still use a partial type hint, `_`, with the turbofish:
1453 /// let a = [1, 2, 3];
1455 /// let doubled = a.iter()
1456 /// .map(|&x| x * 2)
1457 /// .collect::<Vec<_>>();
1459 /// assert_eq!(vec![2, 4, 6], doubled);
1462 /// Using `collect()` to make a [`String`]:
1465 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1467 /// let hello: String = chars.iter()
1468 /// .map(|&x| x as u8)
1469 /// .map(|x| (x + 1) as char)
1472 /// assert_eq!("hello", hello);
1475 /// If you have a list of [`Result<T, E>`]s, you can use `collect()` to
1476 /// see if any of them failed:
1479 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1481 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1483 /// // gives us the first error
1484 /// assert_eq!(Err("nope"), result);
1486 /// let results = [Ok(1), Ok(3)];
1488 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1490 /// // gives us the list of answers
1491 /// assert_eq!(Ok(vec![1, 3]), result);
1494 #[stable(feature = "rust1", since = "1.0.0")]
1495 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1496 FromIterator::from_iter(self)
1499 /// Consumes an iterator, creating two collections from it.
1501 /// The predicate passed to `partition()` can return `true`, or `false`.
1502 /// `partition()` returns a pair, all of the elements for which it returned
1503 /// `true`, and all of the elements for which it returned `false`.
1510 /// let a = [1, 2, 3];
1512 /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1513 /// .partition(|&n| n % 2 == 0);
1515 /// assert_eq!(even, vec![2]);
1516 /// assert_eq!(odd, vec![1, 3]);
1518 #[stable(feature = "rust1", since = "1.0.0")]
1519 fn partition<B, F>(self, mut f: F) -> (B, B) where
1521 B: Default + Extend<Self::Item>,
1522 F: FnMut(&Self::Item) -> bool
1524 let mut left: B = Default::default();
1525 let mut right: B = Default::default();
1529 left.extend(Some(x))
1531 right.extend(Some(x))
1538 /// An iterator adaptor that applies a function, producing a single, final value.
1540 /// `fold()` takes two arguments: an initial value, and a closure with two
1541 /// arguments: an 'accumulator', and an element. The closure returns the value that
1542 /// the accumulator should have for the next iteration.
1544 /// The initial value is the value the accumulator will have on the first
1547 /// After applying this closure to every element of the iterator, `fold()`
1548 /// returns the accumulator.
1550 /// This operation is sometimes called 'reduce' or 'inject'.
1552 /// Folding is useful whenever you have a collection of something, and want
1553 /// to produce a single value from it.
1560 /// let a = [1, 2, 3];
1562 /// // the sum of all of the elements of a
1563 /// let sum = a.iter()
1564 /// .fold(0, |acc, &x| acc + x);
1566 /// assert_eq!(sum, 6);
1569 /// Let's walk through each step of the iteration here:
1571 /// | element | acc | x | result |
1572 /// |---------|-----|---|--------|
1574 /// | 1 | 0 | 1 | 1 |
1575 /// | 2 | 1 | 2 | 3 |
1576 /// | 3 | 3 | 3 | 6 |
1578 /// And so, our final result, `6`.
1580 /// It's common for people who haven't used iterators a lot to
1581 /// use a `for` loop with a list of things to build up a result. Those
1582 /// can be turned into `fold()`s:
1585 /// let numbers = [1, 2, 3, 4, 5];
1587 /// let mut result = 0;
1590 /// for i in &numbers {
1591 /// result = result + i;
1595 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1597 /// // they're the same
1598 /// assert_eq!(result, result2);
1601 #[stable(feature = "rust1", since = "1.0.0")]
1602 fn fold<B, F>(self, init: B, mut f: F) -> B where
1603 Self: Sized, F: FnMut(B, Self::Item) -> B,
1605 let mut accum = init;
1607 accum = f(accum, x);
1612 /// Tests if every element of the iterator matches a predicate.
1614 /// `all()` takes a closure that returns `true` or `false`. It applies
1615 /// this closure to each element of the iterator, and if they all return
1616 /// `true`, then so does `all()`. If any of them return `false`, it
1617 /// returns `false`.
1619 /// `all()` is short-circuiting; in other words, it will stop processing
1620 /// as soon as it finds a `false`, given that no matter what else happens,
1621 /// the result will also be `false`.
1623 /// An empty iterator returns `true`.
1630 /// let a = [1, 2, 3];
1632 /// assert!(a.iter().all(|&x| x > 0));
1634 /// assert!(!a.iter().all(|&x| x > 2));
1637 /// Stopping at the first `false`:
1640 /// let a = [1, 2, 3];
1642 /// let mut iter = a.iter();
1644 /// assert!(!iter.all(|&x| x != 2));
1646 /// // we can still use `iter`, as there are more elements.
1647 /// assert_eq!(iter.next(), Some(&3));
1650 #[stable(feature = "rust1", since = "1.0.0")]
1651 fn all<F>(&mut self, mut f: F) -> bool where
1652 Self: Sized, F: FnMut(Self::Item) -> bool
1662 /// Tests if any element of the iterator matches a predicate.
1664 /// `any()` takes a closure that returns `true` or `false`. It applies
1665 /// this closure to each element of the iterator, and if any of them return
1666 /// `true`, then so does `any()`. If they all return `false`, it
1667 /// returns `false`.
1669 /// `any()` is short-circuiting; in other words, it will stop processing
1670 /// as soon as it finds a `true`, given that no matter what else happens,
1671 /// the result will also be `true`.
1673 /// An empty iterator returns `false`.
1680 /// let a = [1, 2, 3];
1682 /// assert!(a.iter().any(|&x| x > 0));
1684 /// assert!(!a.iter().any(|&x| x > 5));
1687 /// Stopping at the first `true`:
1690 /// let a = [1, 2, 3];
1692 /// let mut iter = a.iter();
1694 /// assert!(iter.any(|&x| x != 2));
1696 /// // we can still use `iter`, as there are more elements.
1697 /// assert_eq!(iter.next(), Some(&2));
1700 #[stable(feature = "rust1", since = "1.0.0")]
1701 fn any<F>(&mut self, mut f: F) -> bool where
1703 F: FnMut(Self::Item) -> bool
1713 /// Searches for an element of an iterator that satisfies a predicate.
1715 /// `find()` takes a closure that returns `true` or `false`. It applies
1716 /// this closure to each element of the iterator, and if any of them return
1717 /// `true`, then `find()` returns `Some(element)`. If they all return
1718 /// `false`, it returns `None`.
1720 /// `find()` is short-circuiting; in other words, it will stop processing
1721 /// as soon as the closure returns `true`.
1723 /// Because `find()` takes a reference, and many iterators iterate over
1724 /// references, this leads to a possibly confusing situation where the
1725 /// argument is a double reference. You can see this effect in the
1726 /// examples below, with `&&x`.
1733 /// let a = [1, 2, 3];
1735 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1737 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1740 /// Stopping at the first `true`:
1743 /// let a = [1, 2, 3];
1745 /// let mut iter = a.iter();
1747 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1749 /// // we can still use `iter`, as there are more elements.
1750 /// assert_eq!(iter.next(), Some(&3));
1753 #[stable(feature = "rust1", since = "1.0.0")]
1754 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1756 P: FnMut(&Self::Item) -> bool,
1759 if predicate(&x) { return Some(x) }
1764 /// Searches for an element in an iterator, returning its index.
1766 /// `position()` takes a closure that returns `true` or `false`. It applies
1767 /// this closure to each element of the iterator, and if one of them
1768 /// returns `true`, then `position()` returns `Some(index)`. If all of
1769 /// them return `false`, it returns `None`.
1771 /// `position()` is short-circuiting; in other words, it will stop
1772 /// processing as soon as it finds a `true`.
1774 /// # Overflow Behavior
1776 /// The method does no guarding against overflows, so if there are more
1777 /// than `usize::MAX` non-matching elements, it either produces the wrong
1778 /// result or panics. If debug assertions are enabled, a panic is
1783 /// This function might panic if the iterator has more than `usize::MAX`
1784 /// non-matching elements.
1791 /// let a = [1, 2, 3];
1793 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1795 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1798 /// Stopping at the first `true`:
1801 /// let a = [1, 2, 3];
1803 /// let mut iter = a.iter();
1805 /// assert_eq!(iter.position(|&x| x == 2), Some(1));
1807 /// // we can still use `iter`, as there are more elements.
1808 /// assert_eq!(iter.next(), Some(&3));
1811 #[stable(feature = "rust1", since = "1.0.0")]
1812 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1814 P: FnMut(Self::Item) -> bool,
1816 // `enumerate` might overflow.
1817 for (i, x) in self.enumerate() {
1825 /// Searches for an element in an iterator from the right, returning its
1828 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1829 /// this closure to each element of the iterator, starting from the end,
1830 /// and if one of them returns `true`, then `rposition()` returns
1831 /// `Some(index)`. If all of them return `false`, it returns `None`.
1833 /// `rposition()` is short-circuiting; in other words, it will stop
1834 /// processing as soon as it finds a `true`.
1841 /// let a = [1, 2, 3];
1843 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1845 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1848 /// Stopping at the first `true`:
1851 /// let a = [1, 2, 3];
1853 /// let mut iter = a.iter();
1855 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1857 /// // we can still use `iter`, as there are more elements.
1858 /// assert_eq!(iter.next(), Some(&1));
1861 #[stable(feature = "rust1", since = "1.0.0")]
1862 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1863 P: FnMut(Self::Item) -> bool,
1864 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1866 let mut i = self.len();
1868 while let Some(v) = self.next_back() {
1872 // No need for an overflow check here, because `ExactSizeIterator`
1873 // implies that the number of elements fits into a `usize`.
1879 /// Returns the maximum element of an iterator.
1881 /// If the two elements are equally maximum, the latest element is
1889 /// let a = [1, 2, 3];
1891 /// assert_eq!(a.iter().max(), Some(&3));
1894 #[stable(feature = "rust1", since = "1.0.0")]
1895 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1899 // switch to y even if it is only equal, to preserve
1901 |_, x, _, y| *x <= *y)
1905 /// Returns the minimum element of an iterator.
1907 /// If the two elements are equally minimum, the first element is
1915 /// let a = [1, 2, 3];
1917 /// assert_eq!(a.iter().min(), Some(&1));
1920 #[stable(feature = "rust1", since = "1.0.0")]
1921 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1925 // only switch to y if it is strictly smaller, to
1926 // preserve stability.
1927 |_, x, _, y| *x > *y)
1931 /// Returns the element that gives the maximum value from the
1932 /// specified function.
1934 /// Returns the rightmost element if the comparison determines two elements
1935 /// to be equally maximum.
1940 /// let a = [-3_i32, 0, 1, 5, -10];
1941 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1944 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1945 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1946 where Self: Sized, F: FnMut(&Self::Item) -> B,
1950 // switch to y even if it is only equal, to preserve
1952 |x_p, _, y_p, _| x_p <= y_p)
1956 /// Returns the element that gives the minimum value from the
1957 /// specified function.
1959 /// Returns the latest element if the comparison determines two elements
1960 /// to be equally minimum.
1965 /// let a = [-3_i32, 0, 1, 5, -10];
1966 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
1968 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1969 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1970 where Self: Sized, F: FnMut(&Self::Item) -> B,
1974 // only switch to y if it is strictly smaller, to
1975 // preserve stability.
1976 |x_p, _, y_p, _| x_p > y_p)
1980 /// Reverses an iterator's direction.
1982 /// Usually, iterators iterate from left to right. After using `rev()`,
1983 /// an iterator will instead iterate from right to left.
1985 /// This is only possible if the iterator has an end, so `rev()` only
1986 /// works on [`DoubleEndedIterator`]s.
1988 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1993 /// let a = [1, 2, 3];
1995 /// let mut iter = a.iter().rev();
1997 /// assert_eq!(iter.next(), Some(&3));
1998 /// assert_eq!(iter.next(), Some(&2));
1999 /// assert_eq!(iter.next(), Some(&1));
2001 /// assert_eq!(iter.next(), None);
2004 #[stable(feature = "rust1", since = "1.0.0")]
2005 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
2009 /// Converts an iterator of pairs into a pair of containers.
2011 /// `unzip()` consumes an entire iterator of pairs, producing two
2012 /// collections: one from the left elements of the pairs, and one
2013 /// from the right elements.
2015 /// This function is, in some sense, the opposite of [`zip()`].
2017 /// [`zip()`]: #method.zip
2024 /// let a = [(1, 2), (3, 4)];
2026 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2028 /// assert_eq!(left, [1, 3]);
2029 /// assert_eq!(right, [2, 4]);
2031 #[stable(feature = "rust1", since = "1.0.0")]
2032 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
2033 FromA: Default + Extend<A>,
2034 FromB: Default + Extend<B>,
2035 Self: Sized + Iterator<Item=(A, B)>,
2037 struct SizeHint<A>(usize, Option<usize>, marker::PhantomData<A>);
2038 impl<A> Iterator for SizeHint<A> {
2041 fn next(&mut self) -> Option<A> { None }
2042 fn size_hint(&self) -> (usize, Option<usize>) {
2047 let (lo, hi) = self.size_hint();
2048 let mut ts: FromA = Default::default();
2049 let mut us: FromB = Default::default();
2051 ts.extend(SizeHint(lo, hi, marker::PhantomData));
2052 us.extend(SizeHint(lo, hi, marker::PhantomData));
2054 for (t, u) in self {
2062 /// Creates an iterator which `clone()`s all of its elements.
2064 /// This is useful when you have an iterator over `&T`, but you need an
2065 /// iterator over `T`.
2072 /// let a = [1, 2, 3];
2074 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2076 /// // cloned is the same as .map(|&x| x), for integers
2077 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2079 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2080 /// assert_eq!(v_map, vec![1, 2, 3]);
2082 #[stable(feature = "rust1", since = "1.0.0")]
2083 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2084 where Self: Sized + Iterator<Item=&'a T>, T: Clone
2089 /// Repeats an iterator endlessly.
2091 /// Instead of stopping at `None`, the iterator will instead start again,
2092 /// from the beginning. After iterating again, it will start at the
2093 /// beginning again. And again. And again. Forever.
2100 /// let a = [1, 2, 3];
2102 /// let mut it = a.iter().cycle();
2104 /// assert_eq!(it.next(), Some(&1));
2105 /// assert_eq!(it.next(), Some(&2));
2106 /// assert_eq!(it.next(), Some(&3));
2107 /// assert_eq!(it.next(), Some(&1));
2108 /// assert_eq!(it.next(), Some(&2));
2109 /// assert_eq!(it.next(), Some(&3));
2110 /// assert_eq!(it.next(), Some(&1));
2112 #[stable(feature = "rust1", since = "1.0.0")]
2114 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
2115 Cycle{orig: self.clone(), iter: self}
2118 /// Sums the elements of an iterator.
2120 /// Takes each element, adds them together, and returns the result.
2122 /// An empty iterator returns the zero value of the type.
2129 /// #![feature(iter_arith)]
2131 /// let a = [1, 2, 3];
2132 /// let sum: i32 = a.iter().sum();
2134 /// assert_eq!(sum, 6);
2136 #[unstable(feature = "iter_arith", reason = "bounds recently changed",
2138 fn sum<S>(self) -> S where
2139 S: Add<Self::Item, Output=S> + Zero,
2142 self.fold(Zero::zero(), |s, e| s + e)
2145 /// Iterates over the entire iterator, multiplying all the elements
2147 /// An empty iterator returns the one value of the type.
2152 /// #![feature(iter_arith)]
2154 /// fn factorial(n: u32) -> u32 {
2155 /// (1..).take_while(|&i| i <= n).product()
2157 /// assert_eq!(factorial(0), 1);
2158 /// assert_eq!(factorial(1), 1);
2159 /// assert_eq!(factorial(5), 120);
2161 #[unstable(feature="iter_arith", reason = "bounds recently changed",
2163 fn product<P>(self) -> P where
2164 P: Mul<Self::Item, Output=P> + One,
2167 self.fold(One::one(), |p, e| p * e)
2170 /// Lexicographically compares the elements of this `Iterator` with those
2172 #[stable(feature = "iter_order", since = "1.5.0")]
2173 fn cmp<I>(mut self, other: I) -> Ordering where
2174 I: IntoIterator<Item = Self::Item>,
2178 let mut other = other.into_iter();
2181 match (self.next(), other.next()) {
2182 (None, None) => return Ordering::Equal,
2183 (None, _ ) => return Ordering::Less,
2184 (_ , None) => return Ordering::Greater,
2185 (Some(x), Some(y)) => match x.cmp(&y) {
2186 Ordering::Equal => (),
2187 non_eq => return non_eq,
2193 /// Lexicographically compares the elements of this `Iterator` with those
2195 #[stable(feature = "iter_order", since = "1.5.0")]
2196 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2198 Self::Item: PartialOrd<I::Item>,
2201 let mut other = other.into_iter();
2204 match (self.next(), other.next()) {
2205 (None, None) => return Some(Ordering::Equal),
2206 (None, _ ) => return Some(Ordering::Less),
2207 (_ , None) => return Some(Ordering::Greater),
2208 (Some(x), Some(y)) => match x.partial_cmp(&y) {
2209 Some(Ordering::Equal) => (),
2210 non_eq => return non_eq,
2216 /// Determines if the elements of this `Iterator` are equal to those of
2218 #[stable(feature = "iter_order", since = "1.5.0")]
2219 fn eq<I>(mut self, other: I) -> bool where
2221 Self::Item: PartialEq<I::Item>,
2224 let mut other = other.into_iter();
2227 match (self.next(), other.next()) {
2228 (None, None) => return true,
2229 (None, _) | (_, None) => return false,
2230 (Some(x), Some(y)) => if x != y { return false },
2235 /// Determines if the elements of this `Iterator` are unequal to those of
2237 #[stable(feature = "iter_order", since = "1.5.0")]
2238 fn ne<I>(mut self, other: I) -> bool where
2240 Self::Item: PartialEq<I::Item>,
2243 let mut other = other.into_iter();
2246 match (self.next(), other.next()) {
2247 (None, None) => return false,
2248 (None, _) | (_, None) => return true,
2249 (Some(x), Some(y)) => if x.ne(&y) { return true },
2254 /// Determines if the elements of this `Iterator` are lexicographically
2255 /// less than those of another.
2256 #[stable(feature = "iter_order", since = "1.5.0")]
2257 fn lt<I>(mut self, other: I) -> bool where
2259 Self::Item: PartialOrd<I::Item>,
2262 let mut other = other.into_iter();
2265 match (self.next(), other.next()) {
2266 (None, None) => return false,
2267 (None, _ ) => return true,
2268 (_ , None) => return false,
2269 (Some(x), Some(y)) => {
2270 match x.partial_cmp(&y) {
2271 Some(Ordering::Less) => return true,
2272 Some(Ordering::Equal) => {}
2273 Some(Ordering::Greater) => return false,
2274 None => return false,
2281 /// Determines if the elements of this `Iterator` are lexicographically
2282 /// less or equal to those of another.
2283 #[stable(feature = "iter_order", since = "1.5.0")]
2284 fn le<I>(mut self, other: I) -> bool where
2286 Self::Item: PartialOrd<I::Item>,
2289 let mut other = other.into_iter();
2292 match (self.next(), other.next()) {
2293 (None, None) => return true,
2294 (None, _ ) => return true,
2295 (_ , None) => return false,
2296 (Some(x), Some(y)) => {
2297 match x.partial_cmp(&y) {
2298 Some(Ordering::Less) => return true,
2299 Some(Ordering::Equal) => {}
2300 Some(Ordering::Greater) => return false,
2301 None => return false,
2308 /// Determines if the elements of this `Iterator` are lexicographically
2309 /// greater than those of another.
2310 #[stable(feature = "iter_order", since = "1.5.0")]
2311 fn gt<I>(mut self, other: I) -> bool where
2313 Self::Item: PartialOrd<I::Item>,
2316 let mut other = other.into_iter();
2319 match (self.next(), other.next()) {
2320 (None, None) => return false,
2321 (None, _ ) => return false,
2322 (_ , None) => return true,
2323 (Some(x), Some(y)) => {
2324 match x.partial_cmp(&y) {
2325 Some(Ordering::Less) => return false,
2326 Some(Ordering::Equal) => {}
2327 Some(Ordering::Greater) => return true,
2328 None => return false,
2335 /// Determines if the elements of this `Iterator` are lexicographically
2336 /// greater than or equal to those of another.
2337 #[stable(feature = "iter_order", since = "1.5.0")]
2338 fn ge<I>(mut self, other: I) -> bool where
2340 Self::Item: PartialOrd<I::Item>,
2343 let mut other = other.into_iter();
2346 match (self.next(), other.next()) {
2347 (None, None) => return true,
2348 (None, _ ) => return false,
2349 (_ , None) => return true,
2350 (Some(x), Some(y)) => {
2351 match x.partial_cmp(&y) {
2352 Some(Ordering::Less) => return false,
2353 Some(Ordering::Equal) => {}
2354 Some(Ordering::Greater) => return true,
2355 None => return false,
2363 /// Select an element from an iterator based on the given projection
2364 /// and "comparison" function.
2366 /// This is an idiosyncratic helper to try to factor out the
2367 /// commonalities of {max,min}{,_by}. In particular, this avoids
2368 /// having to implement optimizations several times.
2370 fn select_fold1<I,B, FProj, FCmp>(mut it: I,
2372 mut f_cmp: FCmp) -> Option<(B, I::Item)>
2374 FProj: FnMut(&I::Item) -> B,
2375 FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2377 // start with the first element as our selection. This avoids
2378 // having to use `Option`s inside the loop, translating to a
2379 // sizeable performance gain (6x in one case).
2380 it.next().map(|mut sel| {
2381 let mut sel_p = f_proj(&sel);
2384 let x_p = f_proj(&x);
2385 if f_cmp(&sel_p, &sel, &x_p, &x) {
2394 #[stable(feature = "rust1", since = "1.0.0")]
2395 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2396 type Item = I::Item;
2397 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2398 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2401 /// Conversion from an `Iterator`.
2403 /// By implementing `FromIterator` for a type, you define how it will be
2404 /// created from an iterator. This is common for types which describe a
2405 /// collection of some kind.
2407 /// `FromIterator`'s [`from_iter()`] is rarely called explicitly, and is instead
2408 /// used through [`Iterator`]'s [`collect()`] method. See [`collect()`]'s
2409 /// documentation for more examples.
2411 /// [`from_iter()`]: #tymethod.from_iter
2412 /// [`Iterator`]: trait.Iterator.html
2413 /// [`collect()`]: trait.Iterator.html#method.collect
2415 /// See also: [`IntoIterator`].
2417 /// [`IntoIterator`]: trait.IntoIterator.html
2424 /// use std::iter::FromIterator;
2426 /// let five_fives = std::iter::repeat(5).take(5);
2428 /// let v = Vec::from_iter(five_fives);
2430 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2433 /// Using [`collect()`] to implicitly use `FromIterator`:
2436 /// let five_fives = std::iter::repeat(5).take(5);
2438 /// let v: Vec<i32> = five_fives.collect();
2440 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2443 /// Implementing `FromIterator` for your type:
2446 /// use std::iter::FromIterator;
2448 /// // A sample collection, that's just a wrapper over Vec<T>
2449 /// #[derive(Debug)]
2450 /// struct MyCollection(Vec<i32>);
2452 /// // Let's give it some methods so we can create one and add things
2454 /// impl MyCollection {
2455 /// fn new() -> MyCollection {
2456 /// MyCollection(Vec::new())
2459 /// fn add(&mut self, elem: i32) {
2460 /// self.0.push(elem);
2464 /// // and we'll implement FromIterator
2465 /// impl FromIterator<i32> for MyCollection {
2466 /// fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self {
2467 /// let mut c = MyCollection::new();
2477 /// // Now we can make a new iterator...
2478 /// let iter = (0..5).into_iter();
2480 /// // ... and make a MyCollection out of it
2481 /// let c = MyCollection::from_iter(iter);
2483 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
2485 /// // collect works too!
2487 /// let iter = (0..5).into_iter();
2488 /// let c: MyCollection = iter.collect();
2490 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
2492 #[stable(feature = "rust1", since = "1.0.0")]
2493 #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
2494 built from an iterator over elements of type `{A}`"]
2495 pub trait FromIterator<A>: Sized {
2496 /// Creates a value from an iterator.
2498 /// See the [module-level documentation] for more.
2500 /// [module-level documentation]: trait.FromIterator.html
2507 /// use std::iter::FromIterator;
2509 /// let five_fives = std::iter::repeat(5).take(5);
2511 /// let v = Vec::from_iter(five_fives);
2513 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2515 #[stable(feature = "rust1", since = "1.0.0")]
2516 fn from_iter<T: IntoIterator<Item=A>>(iter: T) -> Self;
2519 /// Conversion into an `Iterator`.
2521 /// By implementing `IntoIterator` for a type, you define how it will be
2522 /// converted to an iterator. This is common for types which describe a
2523 /// collection of some kind.
2525 /// One benefit of implementing `IntoIterator` is that your type will [work
2526 /// with Rust's `for` loop syntax](index.html#for-loops-and-intoiterator).
2528 /// See also: [`FromIterator`].
2530 /// [`FromIterator`]: trait.FromIterator.html
2537 /// let v = vec![1, 2, 3];
2539 /// let mut iter = v.into_iter();
2541 /// let n = iter.next();
2542 /// assert_eq!(Some(1), n);
2544 /// let n = iter.next();
2545 /// assert_eq!(Some(2), n);
2547 /// let n = iter.next();
2548 /// assert_eq!(Some(3), n);
2550 /// let n = iter.next();
2551 /// assert_eq!(None, n);
2554 /// Implementing `IntoIterator` for your type:
2557 /// // A sample collection, that's just a wrapper over Vec<T>
2558 /// #[derive(Debug)]
2559 /// struct MyCollection(Vec<i32>);
2561 /// // Let's give it some methods so we can create one and add things
2563 /// impl MyCollection {
2564 /// fn new() -> MyCollection {
2565 /// MyCollection(Vec::new())
2568 /// fn add(&mut self, elem: i32) {
2569 /// self.0.push(elem);
2573 /// // and we'll implement IntoIterator
2574 /// impl IntoIterator for MyCollection {
2575 /// type Item = i32;
2576 /// type IntoIter = ::std::vec::IntoIter<i32>;
2578 /// fn into_iter(self) -> Self::IntoIter {
2579 /// self.0.into_iter()
2583 /// // Now we can make a new collection...
2584 /// let mut c = MyCollection::new();
2586 /// // ... add some stuff to it ...
2591 /// // ... and then turn it into an Iterator:
2592 /// for (i, n) in c.into_iter().enumerate() {
2593 /// assert_eq!(i as i32, n);
2596 #[stable(feature = "rust1", since = "1.0.0")]
2597 pub trait IntoIterator {
2598 /// The type of the elements being iterated over.
2599 #[stable(feature = "rust1", since = "1.0.0")]
2602 /// Which kind of iterator are we turning this into?
2603 #[stable(feature = "rust1", since = "1.0.0")]
2604 type IntoIter: Iterator<Item=Self::Item>;
2606 /// Creates an iterator from a value.
2608 /// See the [module-level documentation] for more.
2610 /// [module-level documentation]: trait.IntoIterator.html
2617 /// let v = vec![1, 2, 3];
2619 /// let mut iter = v.into_iter();
2621 /// let n = iter.next();
2622 /// assert_eq!(Some(1), n);
2624 /// let n = iter.next();
2625 /// assert_eq!(Some(2), n);
2627 /// let n = iter.next();
2628 /// assert_eq!(Some(3), n);
2630 /// let n = iter.next();
2631 /// assert_eq!(None, n);
2633 #[stable(feature = "rust1", since = "1.0.0")]
2634 fn into_iter(self) -> Self::IntoIter;
2637 #[stable(feature = "rust1", since = "1.0.0")]
2638 impl<I: Iterator> IntoIterator for I {
2639 type Item = I::Item;
2642 fn into_iter(self) -> I {
2647 /// Extend a collection with the contents of an iterator.
2649 /// Iterators produce a series of values, and collections can also be thought
2650 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
2651 /// to extend a collection by including the contents of that iterator.
2658 /// // You can extend a String with some chars:
2659 /// let mut message = String::from("The first three letters are: ");
2661 /// message.extend(&['a', 'b', 'c']);
2663 /// assert_eq!("abc", &message[29..32]);
2666 /// Implementing `Extend`:
2669 /// // A sample collection, that's just a wrapper over Vec<T>
2670 /// #[derive(Debug)]
2671 /// struct MyCollection(Vec<i32>);
2673 /// // Let's give it some methods so we can create one and add things
2675 /// impl MyCollection {
2676 /// fn new() -> MyCollection {
2677 /// MyCollection(Vec::new())
2680 /// fn add(&mut self, elem: i32) {
2681 /// self.0.push(elem);
2685 /// // since MyCollection has a list of i32s, we implement Extend for i32
2686 /// impl Extend<i32> for MyCollection {
2688 /// // This is a bit simpler with the concrete type signature: we can call
2689 /// // extend on anything which can be turned into an Iterator which gives
2690 /// // us i32s. Because we need i32s to put into MyCollection.
2691 /// fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {
2693 /// // The implementation is very straightforward: loop through the
2694 /// // iterator, and add() each element to ourselves.
2695 /// for elem in iter {
2701 /// let mut c = MyCollection::new();
2707 /// // let's extend our collection with three more numbers
2708 /// c.extend(vec![1, 2, 3]);
2710 /// // we've added these elements onto the end
2711 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
2713 #[stable(feature = "rust1", since = "1.0.0")]
2714 pub trait Extend<A> {
2715 /// Extends a collection with the contents of an iterator.
2717 /// As this is the only method for this trait, the [trait-level] docs
2718 /// contain more details.
2720 /// [trait-level]: trait.Extend.html
2727 /// // You can extend a String with some chars:
2728 /// let mut message = String::from("abc");
2730 /// message.extend(['d', 'e', 'f'].iter());
2732 /// assert_eq!("abcdef", &message);
2734 #[stable(feature = "rust1", since = "1.0.0")]
2735 fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T);
2738 /// An iterator able to yield elements from both ends.
2740 /// Something that implements `DoubleEndedIterator` has one extra capability
2741 /// over something that implements [`Iterator`]: the ability to also take
2742 /// `Item`s from the back, as well as the front.
2744 /// It is important to note that both back and forth work on the same range,
2745 /// and do not cross: iteration is over when they meet in the middle.
2747 /// In a similar fashion to the [`Iterator`] protocol, once a
2748 /// `DoubleEndedIterator` returns `None` from a `next_back()`, calling it again
2749 /// may or may not ever return `Some` again. `next()` and `next_back()` are
2750 /// interchangable for this purpose.
2752 /// [`Iterator`]: trait.Iterator.html
2759 /// let numbers = vec![1, 2, 3];
2761 /// let mut iter = numbers.iter();
2763 /// assert_eq!(Some(&1), iter.next());
2764 /// assert_eq!(Some(&3), iter.next_back());
2765 /// assert_eq!(Some(&2), iter.next_back());
2766 /// assert_eq!(None, iter.next());
2767 /// assert_eq!(None, iter.next_back());
2769 #[stable(feature = "rust1", since = "1.0.0")]
2770 pub trait DoubleEndedIterator: Iterator {
2771 /// An iterator able to yield elements from both ends.
2773 /// As this is the only method for this trait, the [trait-level] docs
2774 /// contain more details.
2776 /// [trait-level]: trait.DoubleEndedIterator.html
2783 /// let numbers = vec![1, 2, 3];
2785 /// let mut iter = numbers.iter();
2787 /// assert_eq!(Some(&1), iter.next());
2788 /// assert_eq!(Some(&3), iter.next_back());
2789 /// assert_eq!(Some(&2), iter.next_back());
2790 /// assert_eq!(None, iter.next());
2791 /// assert_eq!(None, iter.next_back());
2793 #[stable(feature = "rust1", since = "1.0.0")]
2794 fn next_back(&mut self) -> Option<Self::Item>;
2797 #[stable(feature = "rust1", since = "1.0.0")]
2798 impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
2799 fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
2802 /// An iterator that knows its exact length.
2804 /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
2805 /// If an iterator knows how many times it can iterate, providing access to
2806 /// that information can be useful. For example, if you want to iterate
2807 /// backwards, a good start is to know where the end is.
2809 /// When implementing an `ExactSizeIterator`, You must also implement
2810 /// [`Iterator`]. When doing so, the implementation of [`size_hint()`] *must*
2811 /// return the exact size of the iterator.
2813 /// [`Iterator`]: trait.Iterator.html
2814 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
2816 /// The [`len()`] method has a default implementation, so you usually shouldn't
2817 /// implement it. However, you may be able to provide a more performant
2818 /// implementation than the default, so overriding it in this case makes sense.
2820 /// [`len()`]: #method.len
2827 /// // a finite range knows exactly how many times it will iterate
2828 /// let five = 0..5;
2830 /// assert_eq!(5, five.len());
2833 /// In the [module level docs][moddocs], we implemented an [`Iterator`],
2834 /// `Counter`. Let's implement `ExactSizeIterator` for it as well:
2836 /// [moddocs]: index.html
2839 /// # struct Counter {
2842 /// # impl Counter {
2843 /// # fn new() -> Counter {
2844 /// # Counter { count: 0 }
2847 /// # impl Iterator for Counter {
2848 /// # type Item = usize;
2849 /// # fn next(&mut self) -> Option<usize> {
2850 /// # self.count += 1;
2851 /// # if self.count < 6 {
2852 /// # Some(self.count)
2858 /// impl ExactSizeIterator for Counter {
2859 /// // We already have the number of iterations, so we can use it directly.
2860 /// fn len(&self) -> usize {
2865 /// // And now we can use it!
2867 /// let counter = Counter::new();
2869 /// assert_eq!(0, counter.len());
2871 #[stable(feature = "rust1", since = "1.0.0")]
2872 pub trait ExactSizeIterator: Iterator {
2874 #[stable(feature = "rust1", since = "1.0.0")]
2875 /// Returns the exact number of times the iterator will iterate.
2877 /// This method has a default implementation, so you usually should not
2878 /// implement it directly. However, if you can provide a more efficient
2879 /// implementation, you can do so. See the [trait-level] docs for an
2882 /// This function has the same safety guarantees as the [`size_hint()`]
2885 /// [trait-level]: trait.ExactSizeIterator.html
2886 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
2893 /// // a finite range knows exactly how many times it will iterate
2894 /// let five = 0..5;
2896 /// assert_eq!(5, five.len());
2898 fn len(&self) -> usize {
2899 let (lower, upper) = self.size_hint();
2900 // Note: This assertion is overly defensive, but it checks the invariant
2901 // guaranteed by the trait. If this trait were rust-internal,
2902 // we could use debug_assert!; assert_eq! will check all Rust user
2903 // implementations too.
2904 assert_eq!(upper, Some(lower));
2909 #[stable(feature = "rust1", since = "1.0.0")]
2910 impl<'a, I: ExactSizeIterator + ?Sized> ExactSizeIterator for &'a mut I {}
2912 // All adaptors that preserve the size of the wrapped iterator are fine
2913 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
2914 #[stable(feature = "rust1", since = "1.0.0")]
2915 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {}
2916 #[stable(feature = "rust1", since = "1.0.0")]
2917 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F> where
2920 #[stable(feature = "rust1", since = "1.0.0")]
2921 impl<I> ExactSizeIterator for Rev<I>
2922 where I: ExactSizeIterator + DoubleEndedIterator {}
2923 #[stable(feature = "rust1", since = "1.0.0")]
2924 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F> where
2925 F: FnMut(I::Item) -> B,
2927 #[stable(feature = "rust1", since = "1.0.0")]
2928 impl<A, B> ExactSizeIterator for Zip<A, B>
2929 where A: ExactSizeIterator, B: ExactSizeIterator {}
2931 /// An double-ended iterator with the direction inverted.
2933 /// This `struct` is created by the [`rev()`] method on [`Iterator`]. See its
2934 /// documentation for more.
2936 /// [`rev()`]: trait.Iterator.html#method.rev
2937 /// [`Iterator`]: trait.Iterator.html
2938 #[derive(Clone, Debug)]
2939 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2940 #[stable(feature = "rust1", since = "1.0.0")]
2945 #[stable(feature = "rust1", since = "1.0.0")]
2946 impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
2947 type Item = <I as Iterator>::Item;
2950 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
2952 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
2955 #[stable(feature = "rust1", since = "1.0.0")]
2956 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
2958 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
2961 /// An iterator that clones the elements of an underlying iterator.
2963 /// This `struct` is created by the [`cloned()`] method on [`Iterator`]. See its
2964 /// documentation for more.
2966 /// [`cloned()`]: trait.Iterator.html#method.cloned
2967 /// [`Iterator`]: trait.Iterator.html
2968 #[stable(feature = "iter_cloned", since = "1.1.0")]
2969 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2970 #[derive(Clone, Debug)]
2971 pub struct Cloned<I> {
2975 #[stable(feature = "rust1", since = "1.0.0")]
2976 impl<'a, I, T: 'a> Iterator for Cloned<I>
2977 where I: Iterator<Item=&'a T>, T: Clone
2981 fn next(&mut self) -> Option<T> {
2982 self.it.next().cloned()
2985 fn size_hint(&self) -> (usize, Option<usize>) {
2990 #[stable(feature = "rust1", since = "1.0.0")]
2991 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
2992 where I: DoubleEndedIterator<Item=&'a T>, T: Clone
2994 fn next_back(&mut self) -> Option<T> {
2995 self.it.next_back().cloned()
2999 #[stable(feature = "rust1", since = "1.0.0")]
3000 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
3001 where I: ExactSizeIterator<Item=&'a T>, T: Clone
3004 /// An iterator that repeats endlessly.
3006 /// This `struct` is created by the [`cycle()`] method on [`Iterator`]. See its
3007 /// documentation for more.
3009 /// [`cycle()`]: trait.Iterator.html#method.cycle
3010 /// [`Iterator`]: trait.Iterator.html
3011 #[derive(Clone, Debug)]
3012 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3013 #[stable(feature = "rust1", since = "1.0.0")]
3014 pub struct Cycle<I> {
3019 #[stable(feature = "rust1", since = "1.0.0")]
3020 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
3021 type Item = <I as Iterator>::Item;
3024 fn next(&mut self) -> Option<<I as Iterator>::Item> {
3025 match self.iter.next() {
3026 None => { self.iter = self.orig.clone(); self.iter.next() }
3032 fn size_hint(&self) -> (usize, Option<usize>) {
3033 // the cycle iterator is either empty or infinite
3034 match self.orig.size_hint() {
3035 sz @ (0, Some(0)) => sz,
3036 (0, _) => (0, None),
3037 _ => (usize::MAX, None)
3042 /// An iterator that strings two iterators together.
3044 /// This `struct` is created by the [`chain()`] method on [`Iterator`]. See its
3045 /// documentation for more.
3047 /// [`chain()`]: trait.Iterator.html#method.chain
3048 /// [`Iterator`]: trait.Iterator.html
3049 #[derive(Clone, Debug)]
3050 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3051 #[stable(feature = "rust1", since = "1.0.0")]
3052 pub struct Chain<A, B> {
3058 // The iterator protocol specifies that iteration ends with the return value
3059 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
3060 // further calls return. The chain adaptor must account for this since it uses
3061 // two subiterators.
3063 // It uses three states:
3065 // - Both: `a` and `b` are remaining
3066 // - Front: `a` remaining
3067 // - Back: `b` remaining
3069 // The fourth state (neither iterator is remaining) only occurs after Chain has
3070 // returned None once, so we don't need to store this state.
3071 #[derive(Clone, Debug)]
3073 // both front and back iterator are remaining
3075 // only front is remaining
3077 // only back is remaining
3081 #[stable(feature = "rust1", since = "1.0.0")]
3082 impl<A, B> Iterator for Chain<A, B> where
3084 B: Iterator<Item = A::Item>
3086 type Item = A::Item;
3089 fn next(&mut self) -> Option<A::Item> {
3091 ChainState::Both => match self.a.next() {
3092 elt @ Some(..) => elt,
3094 self.state = ChainState::Back;
3098 ChainState::Front => self.a.next(),
3099 ChainState::Back => self.b.next(),
3104 fn count(self) -> usize {
3106 ChainState::Both => self.a.count() + self.b.count(),
3107 ChainState::Front => self.a.count(),
3108 ChainState::Back => self.b.count(),
3113 fn nth(&mut self, mut n: usize) -> Option<A::Item> {
3115 ChainState::Both | ChainState::Front => {
3116 for x in self.a.by_ref() {
3122 if let ChainState::Both = self.state {
3123 self.state = ChainState::Back;
3126 ChainState::Back => {}
3128 if let ChainState::Back = self.state {
3136 fn last(self) -> Option<A::Item> {
3138 ChainState::Both => {
3139 // Must exhaust a before b.
3140 let a_last = self.a.last();
3141 let b_last = self.b.last();
3144 ChainState::Front => self.a.last(),
3145 ChainState::Back => self.b.last()
3150 fn size_hint(&self) -> (usize, Option<usize>) {
3151 let (a_lower, a_upper) = self.a.size_hint();
3152 let (b_lower, b_upper) = self.b.size_hint();
3154 let lower = a_lower.saturating_add(b_lower);
3156 let upper = match (a_upper, b_upper) {
3157 (Some(x), Some(y)) => x.checked_add(y),
3165 #[stable(feature = "rust1", since = "1.0.0")]
3166 impl<A, B> DoubleEndedIterator for Chain<A, B> where
3167 A: DoubleEndedIterator,
3168 B: DoubleEndedIterator<Item=A::Item>,
3171 fn next_back(&mut self) -> Option<A::Item> {
3173 ChainState::Both => match self.b.next_back() {
3174 elt @ Some(..) => elt,
3176 self.state = ChainState::Front;
3180 ChainState::Front => self.a.next_back(),
3181 ChainState::Back => self.b.next_back(),
3186 /// An iterator that iterates two other iterators simultaneously.
3188 /// This `struct` is created by the [`zip()`] method on [`Iterator`]. See its
3189 /// documentation for more.
3191 /// [`zip()`]: trait.Iterator.html#method.zip
3192 /// [`Iterator`]: trait.Iterator.html
3193 #[derive(Clone, Debug)]
3194 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3195 #[stable(feature = "rust1", since = "1.0.0")]
3196 pub struct Zip<A, B> {
3201 #[stable(feature = "rust1", since = "1.0.0")]
3202 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
3204 type Item = (A::Item, B::Item);
3207 fn next(&mut self) -> Option<(A::Item, B::Item)> {
3208 self.a.next().and_then(|x| {
3209 self.b.next().and_then(|y| {
3216 fn size_hint(&self) -> (usize, Option<usize>) {
3217 let (a_lower, a_upper) = self.a.size_hint();
3218 let (b_lower, b_upper) = self.b.size_hint();
3220 let lower = cmp::min(a_lower, b_lower);
3222 let upper = match (a_upper, b_upper) {
3223 (Some(x), Some(y)) => Some(cmp::min(x,y)),
3224 (Some(x), None) => Some(x),
3225 (None, Some(y)) => Some(y),
3226 (None, None) => None
3233 #[stable(feature = "rust1", since = "1.0.0")]
3234 impl<A, B> DoubleEndedIterator for Zip<A, B> where
3235 A: DoubleEndedIterator + ExactSizeIterator,
3236 B: DoubleEndedIterator + ExactSizeIterator,
3239 fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
3240 let a_sz = self.a.len();
3241 let b_sz = self.b.len();
3243 // Adjust a, b to equal length
3245 for _ in 0..a_sz - b_sz { self.a.next_back(); }
3247 for _ in 0..b_sz - a_sz { self.b.next_back(); }
3250 match (self.a.next_back(), self.b.next_back()) {
3251 (Some(x), Some(y)) => Some((x, y)),
3252 (None, None) => None,
3253 _ => unreachable!(),
3258 /// An iterator that maps the values of `iter` with `f`.
3260 /// This `struct` is created by the [`map()`] method on [`Iterator`]. See its
3261 /// documentation for more.
3263 /// [`map()`]: trait.Iterator.html#method.map
3264 /// [`Iterator`]: trait.Iterator.html
3266 /// # Notes about side effects
3268 /// The [`map()`] iterator implements [`DoubleEndedIterator`], meaning that
3269 /// you can also [`map()`] backwards:
3272 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().rev().map(|x| x + 1).collect();
3274 /// assert_eq!(v, [4, 3, 2]);
3277 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
3279 /// But if your closure has state, iterating backwards may act in a way you do
3280 /// not expect. Let's go through an example. First, in the forward direction:
3285 /// for pair in vec!['a', 'b', 'c'].into_iter()
3286 /// .map(|letter| { c += 1; (letter, c) }) {
3287 /// println!("{:?}", pair);
3291 /// This will print "('a', 1), ('b', 2), ('c', 3)".
3293 /// Now consider this twist where we add a call to `rev`. This version will
3294 /// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
3295 /// but the values of the counter still go in order. This is because `map()` is
3296 /// still being called lazilly on each item, but we are popping items off the
3297 /// back of the vector now, instead of shifting them from the front.
3302 /// for pair in vec!['a', 'b', 'c'].into_iter()
3303 /// .map(|letter| { c += 1; (letter, c) })
3305 /// println!("{:?}", pair);
3308 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3309 #[stable(feature = "rust1", since = "1.0.0")]
3311 pub struct Map<I, F> {
3316 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3317 impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
3318 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3319 f.debug_struct("Map")
3320 .field("iter", &self.iter)
3325 #[stable(feature = "rust1", since = "1.0.0")]
3326 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
3330 fn next(&mut self) -> Option<B> {
3331 self.iter.next().map(&mut self.f)
3335 fn size_hint(&self) -> (usize, Option<usize>) {
3336 self.iter.size_hint()
3340 #[stable(feature = "rust1", since = "1.0.0")]
3341 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
3342 F: FnMut(I::Item) -> B,
3345 fn next_back(&mut self) -> Option<B> {
3346 self.iter.next_back().map(&mut self.f)
3350 /// An iterator that filters the elements of `iter` with `predicate`.
3352 /// This `struct` is created by the [`filter()`] method on [`Iterator`]. See its
3353 /// documentation for more.
3355 /// [`filter()`]: trait.Iterator.html#method.filter
3356 /// [`Iterator`]: trait.Iterator.html
3357 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3358 #[stable(feature = "rust1", since = "1.0.0")]
3360 pub struct Filter<I, P> {
3365 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3366 impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
3367 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3368 f.debug_struct("Filter")
3369 .field("iter", &self.iter)
3374 #[stable(feature = "rust1", since = "1.0.0")]
3375 impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
3376 type Item = I::Item;
3379 fn next(&mut self) -> Option<I::Item> {
3380 for x in self.iter.by_ref() {
3381 if (self.predicate)(&x) {
3389 fn size_hint(&self) -> (usize, Option<usize>) {
3390 let (_, upper) = self.iter.size_hint();
3391 (0, upper) // can't know a lower bound, due to the predicate
3395 #[stable(feature = "rust1", since = "1.0.0")]
3396 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
3397 where P: FnMut(&I::Item) -> bool,
3400 fn next_back(&mut self) -> Option<I::Item> {
3401 for x in self.iter.by_ref().rev() {
3402 if (self.predicate)(&x) {
3410 /// An iterator that uses `f` to both filter and map elements from `iter`.
3412 /// This `struct` is created by the [`filter_map()`] method on [`Iterator`]. See its
3413 /// documentation for more.
3415 /// [`filter_map()`]: trait.Iterator.html#method.filter_map
3416 /// [`Iterator`]: trait.Iterator.html
3417 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3418 #[stable(feature = "rust1", since = "1.0.0")]
3420 pub struct FilterMap<I, F> {
3425 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3426 impl<I: fmt::Debug, F> fmt::Debug for FilterMap<I, F> {
3427 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3428 f.debug_struct("FilterMap")
3429 .field("iter", &self.iter)
3434 #[stable(feature = "rust1", since = "1.0.0")]
3435 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
3436 where F: FnMut(I::Item) -> Option<B>,
3441 fn next(&mut self) -> Option<B> {
3442 for x in self.iter.by_ref() {
3443 if let Some(y) = (self.f)(x) {
3451 fn size_hint(&self) -> (usize, Option<usize>) {
3452 let (_, upper) = self.iter.size_hint();
3453 (0, upper) // can't know a lower bound, due to the predicate
3457 #[stable(feature = "rust1", since = "1.0.0")]
3458 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
3459 where F: FnMut(I::Item) -> Option<B>,
3462 fn next_back(&mut self) -> Option<B> {
3463 for x in self.iter.by_ref().rev() {
3464 if let Some(y) = (self.f)(x) {
3472 /// An iterator that yields the current count and the element during iteration.
3474 /// This `struct` is created by the [`enumerate()`] method on [`Iterator`]. See its
3475 /// documentation for more.
3477 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
3478 /// [`Iterator`]: trait.Iterator.html
3479 #[derive(Clone, Debug)]
3480 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3481 #[stable(feature = "rust1", since = "1.0.0")]
3482 pub struct Enumerate<I> {
3487 #[stable(feature = "rust1", since = "1.0.0")]
3488 impl<I> Iterator for Enumerate<I> where I: Iterator {
3489 type Item = (usize, <I as Iterator>::Item);
3491 /// # Overflow Behavior
3493 /// The method does no guarding against overflows, so enumerating more than
3494 /// `usize::MAX` elements either produces the wrong result or panics. If
3495 /// debug assertions are enabled, a panic is guaranteed.
3499 /// Might panic if the index of the element overflows a `usize`.
3501 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
3502 self.iter.next().map(|a| {
3503 let ret = (self.count, a);
3504 // Possible undefined overflow.
3511 fn size_hint(&self) -> (usize, Option<usize>) {
3512 self.iter.size_hint()
3516 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
3517 self.iter.nth(n).map(|a| {
3518 let i = self.count + n;
3525 fn count(self) -> usize {
3530 #[stable(feature = "rust1", since = "1.0.0")]
3531 impl<I> DoubleEndedIterator for Enumerate<I> where
3532 I: ExactSizeIterator + DoubleEndedIterator
3535 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
3536 self.iter.next_back().map(|a| {
3537 let len = self.iter.len();
3538 // Can safely add, `ExactSizeIterator` promises that the number of
3539 // elements fits into a `usize`.
3540 (self.count + len, a)
3545 /// An iterator with a `peek()` that returns an optional reference to the next
3548 /// This `struct` is created by the [`peekable()`] method on [`Iterator`]. See its
3549 /// documentation for more.
3551 /// [`peekable()`]: trait.Iterator.html#method.peekable
3552 /// [`Iterator`]: trait.Iterator.html
3553 #[derive(Clone, Debug)]
3554 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3555 #[stable(feature = "rust1", since = "1.0.0")]
3556 pub struct Peekable<I: Iterator> {
3558 peeked: Option<I::Item>,
3561 #[stable(feature = "rust1", since = "1.0.0")]
3562 impl<I: Iterator> Iterator for Peekable<I> {
3563 type Item = I::Item;
3566 fn next(&mut self) -> Option<I::Item> {
3568 Some(_) => self.peeked.take(),
3569 None => self.iter.next(),
3574 fn count(self) -> usize {
3575 (if self.peeked.is_some() { 1 } else { 0 }) + self.iter.count()
3579 fn nth(&mut self, n: usize) -> Option<I::Item> {
3581 Some(_) if n == 0 => self.peeked.take(),
3586 None => self.iter.nth(n)
3591 fn last(self) -> Option<I::Item> {
3592 self.iter.last().or(self.peeked)
3596 fn size_hint(&self) -> (usize, Option<usize>) {
3597 let (lo, hi) = self.iter.size_hint();
3598 if self.peeked.is_some() {
3599 let lo = lo.saturating_add(1);
3600 let hi = hi.and_then(|x| x.checked_add(1));
3608 #[stable(feature = "rust1", since = "1.0.0")]
3609 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
3611 impl<I: Iterator> Peekable<I> {
3612 /// Returns a reference to the next() value without advancing the iterator.
3614 /// The `peek()` method will return the value that a call to [`next()`] would
3615 /// return, but does not advance the iterator. Like [`next()`], if there is
3616 /// a value, it's wrapped in a `Some(T)`, but if the iterator is over, it
3617 /// will return `None`.
3619 /// [`next()`]: trait.Iterator.html#tymethod.next
3621 /// Because `peek()` returns reference, and many iterators iterate over
3622 /// references, this leads to a possibly confusing situation where the
3623 /// return value is a double reference. You can see this effect in the
3624 /// examples below, with `&&i32`.
3631 /// let xs = [1, 2, 3];
3633 /// let mut iter = xs.iter().peekable();
3635 /// // peek() lets us see into the future
3636 /// assert_eq!(iter.peek(), Some(&&1));
3637 /// assert_eq!(iter.next(), Some(&1));
3639 /// assert_eq!(iter.next(), Some(&2));
3641 /// // we can peek() multiple times, the iterator won't advance
3642 /// assert_eq!(iter.peek(), Some(&&3));
3643 /// assert_eq!(iter.peek(), Some(&&3));
3645 /// assert_eq!(iter.next(), Some(&3));
3647 /// // after the iterator is finished, so is peek()
3648 /// assert_eq!(iter.peek(), None);
3649 /// assert_eq!(iter.next(), None);
3652 #[stable(feature = "rust1", since = "1.0.0")]
3653 pub fn peek(&mut self) -> Option<&I::Item> {
3654 if self.peeked.is_none() {
3655 self.peeked = self.iter.next();
3658 Some(ref value) => Some(value),
3663 /// Checks if the iterator has finished iterating.
3665 /// Returns `true` if there are no more elements in the iterator, and
3666 /// `false` if there are.
3673 /// #![feature(peekable_is_empty)]
3675 /// let xs = [1, 2, 3];
3677 /// let mut iter = xs.iter().peekable();
3679 /// // there are still elements to iterate over
3680 /// assert_eq!(iter.is_empty(), false);
3682 /// // let's consume the iterator
3687 /// assert_eq!(iter.is_empty(), true);
3689 #[unstable(feature = "peekable_is_empty", issue = "32111")]
3691 pub fn is_empty(&mut self) -> bool {
3692 self.peek().is_none()
3696 /// An iterator that rejects elements while `predicate` is true.
3698 /// This `struct` is created by the [`skip_while()`] method on [`Iterator`]. See its
3699 /// documentation for more.
3701 /// [`skip_while()`]: trait.Iterator.html#method.skip_while
3702 /// [`Iterator`]: trait.Iterator.html
3703 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3704 #[stable(feature = "rust1", since = "1.0.0")]
3706 pub struct SkipWhile<I, P> {
3712 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3713 impl<I: fmt::Debug, P> fmt::Debug for SkipWhile<I, P> {
3714 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3715 f.debug_struct("SkipWhile")
3716 .field("iter", &self.iter)
3717 .field("flag", &self.flag)
3722 #[stable(feature = "rust1", since = "1.0.0")]
3723 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
3724 where P: FnMut(&I::Item) -> bool
3726 type Item = I::Item;
3729 fn next(&mut self) -> Option<I::Item> {
3730 for x in self.iter.by_ref() {
3731 if self.flag || !(self.predicate)(&x) {
3740 fn size_hint(&self) -> (usize, Option<usize>) {
3741 let (_, upper) = self.iter.size_hint();
3742 (0, upper) // can't know a lower bound, due to the predicate
3746 /// An iterator that only accepts elements while `predicate` is true.
3748 /// This `struct` is created by the [`take_while()`] method on [`Iterator`]. See its
3749 /// documentation for more.
3751 /// [`take_while()`]: trait.Iterator.html#method.take_while
3752 /// [`Iterator`]: trait.Iterator.html
3753 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3754 #[stable(feature = "rust1", since = "1.0.0")]
3756 pub struct TakeWhile<I, P> {
3762 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3763 impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
3764 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3765 f.debug_struct("TakeWhile")
3766 .field("iter", &self.iter)
3767 .field("flag", &self.flag)
3772 #[stable(feature = "rust1", since = "1.0.0")]
3773 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
3774 where P: FnMut(&I::Item) -> bool
3776 type Item = I::Item;
3779 fn next(&mut self) -> Option<I::Item> {
3783 self.iter.next().and_then(|x| {
3784 if (self.predicate)(&x) {
3795 fn size_hint(&self) -> (usize, Option<usize>) {
3796 let (_, upper) = self.iter.size_hint();
3797 (0, upper) // can't know a lower bound, due to the predicate
3801 /// An iterator that skips over `n` elements of `iter`.
3803 /// This `struct` is created by the [`skip()`] method on [`Iterator`]. See its
3804 /// documentation for more.
3806 /// [`skip()`]: trait.Iterator.html#method.skip
3807 /// [`Iterator`]: trait.Iterator.html
3808 #[derive(Clone, Debug)]
3809 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3810 #[stable(feature = "rust1", since = "1.0.0")]
3811 pub struct Skip<I> {
3816 #[stable(feature = "rust1", since = "1.0.0")]
3817 impl<I> Iterator for Skip<I> where I: Iterator {
3818 type Item = <I as Iterator>::Item;
3821 fn next(&mut self) -> Option<I::Item> {
3827 self.iter.nth(old_n)
3832 fn nth(&mut self, n: usize) -> Option<I::Item> {
3833 // Can't just add n + self.n due to overflow.
3837 let to_skip = self.n;
3840 if self.iter.nth(to_skip-1).is_none() {
3848 fn count(self) -> usize {
3849 self.iter.count().saturating_sub(self.n)
3853 fn last(mut self) -> Option<I::Item> {
3857 let next = self.next();
3859 // recurse. n should be 0.
3860 self.last().or(next)
3868 fn size_hint(&self) -> (usize, Option<usize>) {
3869 let (lower, upper) = self.iter.size_hint();
3871 let lower = lower.saturating_sub(self.n);
3872 let upper = upper.map(|x| x.saturating_sub(self.n));
3878 #[stable(feature = "rust1", since = "1.0.0")]
3879 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
3881 #[stable(feature = "double_ended_skip_iterator", since = "1.8.0")]
3882 impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSizeIterator {
3883 fn next_back(&mut self) -> Option<Self::Item> {
3885 self.iter.next_back()
3892 /// An iterator that only iterates over the first `n` iterations of `iter`.
3894 /// This `struct` is created by the [`take()`] method on [`Iterator`]. See its
3895 /// documentation for more.
3897 /// [`take()`]: trait.Iterator.html#method.take
3898 /// [`Iterator`]: trait.Iterator.html
3899 #[derive(Clone, Debug)]
3900 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3901 #[stable(feature = "rust1", since = "1.0.0")]
3902 pub struct Take<I> {
3907 #[stable(feature = "rust1", since = "1.0.0")]
3908 impl<I> Iterator for Take<I> where I: Iterator{
3909 type Item = <I as Iterator>::Item;
3912 fn next(&mut self) -> Option<<I as Iterator>::Item> {
3922 fn nth(&mut self, n: usize) -> Option<I::Item> {
3928 self.iter.nth(self.n - 1);
3936 fn size_hint(&self) -> (usize, Option<usize>) {
3937 let (lower, upper) = self.iter.size_hint();
3939 let lower = cmp::min(lower, self.n);
3941 let upper = match upper {
3942 Some(x) if x < self.n => Some(x),
3950 #[stable(feature = "rust1", since = "1.0.0")]
3951 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
3954 /// An iterator to maintain state while iterating another iterator.
3956 /// This `struct` is created by the [`scan()`] method on [`Iterator`]. See its
3957 /// documentation for more.
3959 /// [`scan()`]: trait.Iterator.html#method.scan
3960 /// [`Iterator`]: trait.Iterator.html
3961 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3962 #[stable(feature = "rust1", since = "1.0.0")]
3964 pub struct Scan<I, St, F> {
3970 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3971 impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
3972 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3973 f.debug_struct("Scan")
3974 .field("iter", &self.iter)
3975 .field("state", &self.state)
3980 #[stable(feature = "rust1", since = "1.0.0")]
3981 impl<B, I, St, F> Iterator for Scan<I, St, F> where
3983 F: FnMut(&mut St, I::Item) -> Option<B>,
3988 fn next(&mut self) -> Option<B> {
3989 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
3993 fn size_hint(&self) -> (usize, Option<usize>) {
3994 let (_, upper) = self.iter.size_hint();
3995 (0, upper) // can't know a lower bound, due to the scan function
3999 /// An iterator that maps each element to an iterator, and yields the elements
4000 /// of the produced iterators.
4002 /// This `struct` is created by the [`flat_map()`] method on [`Iterator`]. See its
4003 /// documentation for more.
4005 /// [`flat_map()`]: trait.Iterator.html#method.flat_map
4006 /// [`Iterator`]: trait.Iterator.html
4007 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
4008 #[stable(feature = "rust1", since = "1.0.0")]
4010 pub struct FlatMap<I, U: IntoIterator, F> {
4013 frontiter: Option<U::IntoIter>,
4014 backiter: Option<U::IntoIter>,
4017 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4018 impl<I: fmt::Debug, U: IntoIterator, F> fmt::Debug for FlatMap<I, U, F>
4019 where U::IntoIter: fmt::Debug
4021 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4022 f.debug_struct("FlatMap")
4023 .field("iter", &self.iter)
4024 .field("frontiter", &self.frontiter)
4025 .field("backiter", &self.backiter)
4030 #[stable(feature = "rust1", since = "1.0.0")]
4031 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
4032 where F: FnMut(I::Item) -> U,
4034 type Item = U::Item;
4037 fn next(&mut self) -> Option<U::Item> {
4039 if let Some(ref mut inner) = self.frontiter {
4040 if let Some(x) = inner.by_ref().next() {
4044 match self.iter.next().map(&mut self.f) {
4045 None => return self.backiter.as_mut().and_then(|it| it.next()),
4046 next => self.frontiter = next.map(IntoIterator::into_iter),
4052 fn size_hint(&self) -> (usize, Option<usize>) {
4053 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
4054 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
4055 let lo = flo.saturating_add(blo);
4056 match (self.iter.size_hint(), fhi, bhi) {
4057 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
4063 #[stable(feature = "rust1", since = "1.0.0")]
4064 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F> where
4065 F: FnMut(I::Item) -> U,
4067 U::IntoIter: DoubleEndedIterator
4070 fn next_back(&mut self) -> Option<U::Item> {
4072 if let Some(ref mut inner) = self.backiter {
4073 if let Some(y) = inner.next_back() {
4077 match self.iter.next_back().map(&mut self.f) {
4078 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
4079 next => self.backiter = next.map(IntoIterator::into_iter),
4085 /// An iterator that yields `None` forever after the underlying iterator
4086 /// yields `None` once.
4088 /// This `struct` is created by the [`fuse()`] method on [`Iterator`]. See its
4089 /// documentation for more.
4091 /// [`fuse()`]: trait.Iterator.html#method.fuse
4092 /// [`Iterator`]: trait.Iterator.html
4093 #[derive(Clone, Debug)]
4094 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
4095 #[stable(feature = "rust1", since = "1.0.0")]
4096 pub struct Fuse<I> {
4101 #[stable(feature = "rust1", since = "1.0.0")]
4102 impl<I> Iterator for Fuse<I> where I: Iterator {
4103 type Item = <I as Iterator>::Item;
4106 fn next(&mut self) -> Option<<I as Iterator>::Item> {
4110 let next = self.iter.next();
4111 self.done = next.is_none();
4117 fn nth(&mut self, n: usize) -> Option<I::Item> {
4121 let nth = self.iter.nth(n);
4122 self.done = nth.is_none();
4128 fn last(self) -> Option<I::Item> {
4137 fn count(self) -> usize {
4146 fn size_hint(&self) -> (usize, Option<usize>) {
4150 self.iter.size_hint()
4155 #[stable(feature = "rust1", since = "1.0.0")]
4156 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
4158 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
4162 let next = self.iter.next_back();
4163 self.done = next.is_none();
4169 #[stable(feature = "rust1", since = "1.0.0")]
4170 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {}
4172 /// An iterator that calls a function with a reference to each element before
4175 /// This `struct` is created by the [`inspect()`] method on [`Iterator`]. See its
4176 /// documentation for more.
4178 /// [`inspect()`]: trait.Iterator.html#method.inspect
4179 /// [`Iterator`]: trait.Iterator.html
4180 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
4181 #[stable(feature = "rust1", since = "1.0.0")]
4183 pub struct Inspect<I, F> {
4188 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4189 impl<I: fmt::Debug, F> fmt::Debug for Inspect<I, F> {
4190 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4191 f.debug_struct("Inspect")
4192 .field("iter", &self.iter)
4197 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
4199 fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
4200 if let Some(ref a) = elt {
4208 #[stable(feature = "rust1", since = "1.0.0")]
4209 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
4210 type Item = I::Item;
4213 fn next(&mut self) -> Option<I::Item> {
4214 let next = self.iter.next();
4215 self.do_inspect(next)
4219 fn size_hint(&self) -> (usize, Option<usize>) {
4220 self.iter.size_hint()
4224 #[stable(feature = "rust1", since = "1.0.0")]
4225 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
4226 where F: FnMut(&I::Item),
4229 fn next_back(&mut self) -> Option<I::Item> {
4230 let next = self.iter.next_back();
4231 self.do_inspect(next)
4235 /// Objects that can be stepped over in both directions.
4237 /// The `steps_between` function provides a way to efficiently compare
4238 /// two `Step` objects.
4239 #[unstable(feature = "step_trait",
4240 reason = "likely to be replaced by finer-grained traits",
4242 pub trait Step: PartialOrd + Sized {
4243 /// Steps `self` if possible.
4244 fn step(&self, by: &Self) -> Option<Self>;
4246 /// Returns the number of steps between two step objects. The count is
4247 /// inclusive of `start` and exclusive of `end`.
4249 /// Returns `None` if it is not possible to calculate `steps_between`
4250 /// without overflow.
4251 fn steps_between(start: &Self, end: &Self, by: &Self) -> Option<usize>;
4254 macro_rules! step_impl_unsigned {
4256 #[unstable(feature = "step_trait",
4257 reason = "likely to be replaced by finer-grained traits",
4261 fn step(&self, by: &$t) -> Option<$t> {
4262 (*self).checked_add(*by)
4265 #[allow(trivial_numeric_casts)]
4266 fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
4267 if *by == 0 { return None; }
4269 // Note: We assume $t <= usize here
4270 let diff = (*end - *start) as usize;
4271 let by = *by as usize;
4284 macro_rules! step_impl_signed {
4286 #[unstable(feature = "step_trait",
4287 reason = "likely to be replaced by finer-grained traits",
4291 fn step(&self, by: &$t) -> Option<$t> {
4292 (*self).checked_add(*by)
4295 #[allow(trivial_numeric_casts)]
4296 fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
4297 if *by == 0 { return None; }
4304 // Note: We assume $t <= isize here
4305 // Use .wrapping_sub and cast to usize to compute the
4306 // difference that may not fit inside the range of isize.
4307 diff = (*end as isize).wrapping_sub(*start as isize) as usize;
4308 by_u = *by as usize;
4313 diff = (*start as isize).wrapping_sub(*end as isize) as usize;
4314 by_u = (*by as isize).wrapping_mul(-1) as usize;
4316 if diff % by_u > 0 {
4317 Some(diff / by_u + 1)
4326 macro_rules! step_impl_no_between {
4328 #[unstable(feature = "step_trait",
4329 reason = "likely to be replaced by finer-grained traits",
4333 fn step(&self, by: &$t) -> Option<$t> {
4334 (*self).checked_add(*by)
4337 fn steps_between(_a: &$t, _b: &$t, _by: &$t) -> Option<usize> {
4344 step_impl_unsigned!(usize u8 u16 u32);
4345 step_impl_signed!(isize i8 i16 i32);
4346 #[cfg(target_pointer_width = "64")]
4347 step_impl_unsigned!(u64);
4348 #[cfg(target_pointer_width = "64")]
4349 step_impl_signed!(i64);
4350 // If the target pointer width is not 64-bits, we
4351 // assume here that it is less than 64-bits.
4352 #[cfg(not(target_pointer_width = "64"))]
4353 step_impl_no_between!(u64 i64);
4355 /// An adapter for stepping range iterators by a custom amount.
4357 /// The resulting iterator handles overflow by stopping. The `A`
4358 /// parameter is the type being iterated over, while `R` is the range
4359 /// type (usually one of `std::ops::{Range, RangeFrom, RangeInclusive}`.
4360 #[derive(Clone, Debug)]
4361 #[unstable(feature = "step_by", reason = "recent addition",
4363 pub struct StepBy<A, R> {
4368 impl<A: Step> ops::RangeFrom<A> {
4369 /// Creates an iterator starting at the same point, but stepping by
4370 /// the given amount at each iteration.
4375 /// # #![feature(step_by)]
4377 /// for i in (0u8..).step_by(2).take(10) {
4378 /// println!("{}", i);
4382 /// This prints the first ten even natural integers (0 to 18).
4383 #[unstable(feature = "step_by", reason = "recent addition",
4385 pub fn step_by(self, by: A) -> StepBy<A, Self> {
4393 impl<A: Step> ops::Range<A> {
4394 /// Creates an iterator with the same range, but stepping by the
4395 /// given amount at each iteration.
4397 /// The resulting iterator handles overflow by stopping.
4402 /// #![feature(step_by)]
4404 /// for i in (0..10).step_by(2) {
4405 /// println!("{}", i);
4418 #[unstable(feature = "step_by", reason = "recent addition",
4420 pub fn step_by(self, by: A) -> StepBy<A, Self> {
4428 impl<A: Step> ops::RangeInclusive<A> {
4429 /// Creates an iterator with the same range, but stepping by the
4430 /// given amount at each iteration.
4432 /// The resulting iterator handles overflow by stopping.
4437 /// #![feature(step_by, inclusive_range_syntax)]
4439 /// for i in (0...10).step_by(2) {
4440 /// println!("{}", i);
4454 #[unstable(feature = "step_by", reason = "recent addition",
4456 pub fn step_by(self, by: A) -> StepBy<A, Self> {
4464 #[stable(feature = "rust1", since = "1.0.0")]
4465 impl<A> Iterator for StepBy<A, ops::RangeFrom<A>> where
4467 for<'a> &'a A: Add<&'a A, Output = A>
4472 fn next(&mut self) -> Option<A> {
4473 let mut n = &self.range.start + &self.step_by;
4474 mem::swap(&mut n, &mut self.range.start);
4479 fn size_hint(&self) -> (usize, Option<usize>) {
4480 (usize::MAX, None) // Too bad we can't specify an infinite lower bound
4484 #[stable(feature = "rust1", since = "1.0.0")]
4485 impl<A: Step + Zero + Clone> Iterator for StepBy<A, ops::Range<A>> {
4489 fn next(&mut self) -> Option<A> {
4490 let rev = self.step_by < A::zero();
4491 if (rev && self.range.start > self.range.end) ||
4492 (!rev && self.range.start < self.range.end)
4494 match self.range.start.step(&self.step_by) {
4496 mem::swap(&mut self.range.start, &mut n);
4500 let mut n = self.range.end.clone();
4501 mem::swap(&mut self.range.start, &mut n);
4511 fn size_hint(&self) -> (usize, Option<usize>) {
4512 match Step::steps_between(&self.range.start,
4515 Some(hint) => (hint, Some(hint)),
4521 #[unstable(feature = "inclusive_range",
4522 reason = "recently added, follows RFC",
4524 impl<A: Step + Zero + Clone> Iterator for StepBy<A, ops::RangeInclusive<A>> {
4528 fn next(&mut self) -> Option<A> {
4529 use ops::RangeInclusive::*;
4531 // this function has a sort of odd structure due to borrowck issues
4532 // we may need to replace self.range, so borrows of start and end need to end early
4534 let (finishing, n) = match self.range {
4535 Empty { .. } => return None, // empty iterators yield no values
4537 NonEmpty { ref mut start, ref mut end } => {
4538 let zero = A::zero();
4539 let rev = self.step_by < zero;
4541 // march start towards (maybe past!) end and yield the old value
4542 if (rev && start >= end) ||
4543 (!rev && start <= end)
4545 match start.step(&self.step_by) {
4547 mem::swap(start, &mut n);
4548 (None, Some(n)) // yield old value, remain non-empty
4551 let mut n = end.clone();
4552 mem::swap(start, &mut n);
4553 (None, Some(n)) // yield old value, remain non-empty
4557 // found range in inconsistent state (start at or past end), so become empty
4558 (Some(mem::replace(end, zero)), None)
4563 // turn into an empty iterator if we've reached the end
4564 if let Some(end) = finishing {
4565 self.range = Empty { at: end };
4572 fn size_hint(&self) -> (usize, Option<usize>) {
4573 use ops::RangeInclusive::*;
4576 Empty { .. } => (0, Some(0)),
4578 NonEmpty { ref start, ref end } =>
4579 match Step::steps_between(start,
4582 Some(hint) => (hint.saturating_add(1), hint.checked_add(1)),
4589 macro_rules! range_exact_iter_impl {
4591 #[stable(feature = "rust1", since = "1.0.0")]
4592 impl ExactSizeIterator for ops::Range<$t> { }
4594 #[unstable(feature = "inclusive_range",
4595 reason = "recently added, follows RFC",
4597 impl ExactSizeIterator for ops::RangeInclusive<$t> { }
4601 #[stable(feature = "rust1", since = "1.0.0")]
4602 impl<A: Step + One> Iterator for ops::Range<A> where
4603 for<'a> &'a A: Add<&'a A, Output = A>
4608 fn next(&mut self) -> Option<A> {
4609 if self.start < self.end {
4610 let mut n = &self.start + &A::one();
4611 mem::swap(&mut n, &mut self.start);
4619 fn size_hint(&self) -> (usize, Option<usize>) {
4620 match Step::steps_between(&self.start, &self.end, &A::one()) {
4621 Some(hint) => (hint, Some(hint)),
4627 // Ranges of u64 and i64 are excluded because they cannot guarantee having
4628 // a length <= usize::MAX, which is required by ExactSizeIterator.
4629 range_exact_iter_impl!(usize u8 u16 u32 isize i8 i16 i32);
4631 #[stable(feature = "rust1", since = "1.0.0")]
4632 impl<A: Step + One + Clone> DoubleEndedIterator for ops::Range<A> where
4633 for<'a> &'a A: Add<&'a A, Output = A>,
4634 for<'a> &'a A: Sub<&'a A, Output = A>
4637 fn next_back(&mut self) -> Option<A> {
4638 if self.start < self.end {
4639 self.end = &self.end - &A::one();
4640 Some(self.end.clone())
4647 #[stable(feature = "rust1", since = "1.0.0")]
4648 impl<A: Step + One> Iterator for ops::RangeFrom<A> where
4649 for<'a> &'a A: Add<&'a A, Output = A>
4654 fn next(&mut self) -> Option<A> {
4655 let mut n = &self.start + &A::one();
4656 mem::swap(&mut n, &mut self.start);
4661 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
4662 impl<A: Step + One> Iterator for ops::RangeInclusive<A> where
4663 for<'a> &'a A: Add<&'a A, Output = A>
4668 fn next(&mut self) -> Option<A> {
4669 use ops::RangeInclusive::*;
4671 // this function has a sort of odd structure due to borrowck issues
4672 // we may need to replace self, so borrows of self.start and self.end need to end early
4674 let (finishing, n) = match *self {
4675 Empty { .. } => (None, None), // empty iterators yield no values
4677 NonEmpty { ref mut start, ref mut end } => {
4679 (Some(mem::replace(end, A::one())), Some(mem::replace(start, A::one())))
4680 } else if start < end {
4682 let mut n = &*start + &one;
4683 mem::swap(&mut n, start);
4685 // if the iterator is done iterating, it will change from NonEmpty to Empty
4686 // to avoid unnecessary drops or clones, we'll reuse either start or end
4687 // (they are equal now, so it doesn't matter which)
4688 // to pull out end, we need to swap something back in -- use the previously
4689 // created A::one() as a dummy value
4691 (if n == *end { Some(mem::replace(end, one)) } else { None },
4692 // ^ are we done yet?
4693 Some(n)) // < the value to output
4695 (Some(mem::replace(start, A::one())), None)
4700 // turn into an empty iterator if this is the last value
4701 if let Some(end) = finishing {
4702 *self = Empty { at: end };
4709 fn size_hint(&self) -> (usize, Option<usize>) {
4710 use ops::RangeInclusive::*;
4713 Empty { .. } => (0, Some(0)),
4715 NonEmpty { ref start, ref end } =>
4716 match Step::steps_between(start, end, &A::one()) {
4717 Some(hint) => (hint.saturating_add(1), hint.checked_add(1)),
4724 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
4725 impl<A: Step + One> DoubleEndedIterator for ops::RangeInclusive<A> where
4726 for<'a> &'a A: Add<&'a A, Output = A>,
4727 for<'a> &'a A: Sub<&'a A, Output = A>
4730 fn next_back(&mut self) -> Option<A> {
4731 use ops::RangeInclusive::*;
4733 // see Iterator::next for comments
4735 let (finishing, n) = match *self {
4736 Empty { .. } => return None,
4738 NonEmpty { ref mut start, ref mut end } => {
4740 (Some(mem::replace(start, A::one())), Some(mem::replace(end, A::one())))
4741 } else if start < end {
4743 let mut n = &*end - &one;
4744 mem::swap(&mut n, end);
4746 (if n == *start { Some(mem::replace(start, one)) } else { None },
4749 (Some(mem::replace(end, A::one())), None)
4754 if let Some(start) = finishing {
4755 *self = Empty { at: start };
4762 /// An iterator that repeats an element endlessly.
4764 /// This `struct` is created by the [`repeat()`] function. See its documentation for more.
4766 /// [`repeat()`]: fn.repeat.html
4767 #[derive(Clone, Debug)]
4768 #[stable(feature = "rust1", since = "1.0.0")]
4769 pub struct Repeat<A> {
4773 #[stable(feature = "rust1", since = "1.0.0")]
4774 impl<A: Clone> Iterator for Repeat<A> {
4778 fn next(&mut self) -> Option<A> { Some(self.element.clone()) }
4780 fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
4783 #[stable(feature = "rust1", since = "1.0.0")]
4784 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
4786 fn next_back(&mut self) -> Option<A> { Some(self.element.clone()) }
4789 /// Creates a new iterator that endlessly repeats a single element.
4791 /// The `repeat()` function repeats a single value over and over and over and
4792 /// over and over and 🔁.
4794 /// Infinite iterators like `repeat()` are often used with adapters like
4795 /// [`take()`], in order to make them finite.
4797 /// [`take()`]: trait.Iterator.html#method.take
4806 /// // the number four 4ever:
4807 /// let mut fours = iter::repeat(4);
4809 /// assert_eq!(Some(4), fours.next());
4810 /// assert_eq!(Some(4), fours.next());
4811 /// assert_eq!(Some(4), fours.next());
4812 /// assert_eq!(Some(4), fours.next());
4813 /// assert_eq!(Some(4), fours.next());
4815 /// // yup, still four
4816 /// assert_eq!(Some(4), fours.next());
4819 /// Going finite with [`take()`]:
4824 /// // that last example was too many fours. Let's only have four fours.
4825 /// let mut four_fours = iter::repeat(4).take(4);
4827 /// assert_eq!(Some(4), four_fours.next());
4828 /// assert_eq!(Some(4), four_fours.next());
4829 /// assert_eq!(Some(4), four_fours.next());
4830 /// assert_eq!(Some(4), four_fours.next());
4832 /// // ... and now we're done
4833 /// assert_eq!(None, four_fours.next());
4836 #[stable(feature = "rust1", since = "1.0.0")]
4837 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
4838 Repeat{element: elt}
4841 /// An iterator that yields nothing.
4843 /// This `struct` is created by the [`empty()`] function. See its documentation for more.
4845 /// [`empty()`]: fn.empty.html
4846 #[stable(feature = "iter_empty", since = "1.2.0")]
4847 pub struct Empty<T>(marker::PhantomData<T>);
4849 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4850 impl<T> fmt::Debug for Empty<T> {
4851 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4856 #[stable(feature = "iter_empty", since = "1.2.0")]
4857 impl<T> Iterator for Empty<T> {
4860 fn next(&mut self) -> Option<T> {
4864 fn size_hint(&self) -> (usize, Option<usize>){
4869 #[stable(feature = "iter_empty", since = "1.2.0")]
4870 impl<T> DoubleEndedIterator for Empty<T> {
4871 fn next_back(&mut self) -> Option<T> {
4876 #[stable(feature = "iter_empty", since = "1.2.0")]
4877 impl<T> ExactSizeIterator for Empty<T> {
4878 fn len(&self) -> usize {
4883 // not #[derive] because that adds a Clone bound on T,
4884 // which isn't necessary.
4885 #[stable(feature = "iter_empty", since = "1.2.0")]
4886 impl<T> Clone for Empty<T> {
4887 fn clone(&self) -> Empty<T> {
4888 Empty(marker::PhantomData)
4892 // not #[derive] because that adds a Default bound on T,
4893 // which isn't necessary.
4894 #[stable(feature = "iter_empty", since = "1.2.0")]
4895 impl<T> Default for Empty<T> {
4896 fn default() -> Empty<T> {
4897 Empty(marker::PhantomData)
4901 /// Creates an iterator that yields nothing.
4910 /// // this could have been an iterator over i32, but alas, it's just not.
4911 /// let mut nope = iter::empty::<i32>();
4913 /// assert_eq!(None, nope.next());
4915 #[stable(feature = "iter_empty", since = "1.2.0")]
4916 pub fn empty<T>() -> Empty<T> {
4917 Empty(marker::PhantomData)
4920 /// An iterator that yields an element exactly once.
4922 /// This `struct` is created by the [`once()`] function. See its documentation for more.
4924 /// [`once()`]: fn.once.html
4925 #[derive(Clone, Debug)]
4926 #[stable(feature = "iter_once", since = "1.2.0")]
4927 pub struct Once<T> {
4928 inner: ::option::IntoIter<T>
4931 #[stable(feature = "iter_once", since = "1.2.0")]
4932 impl<T> Iterator for Once<T> {
4935 fn next(&mut self) -> Option<T> {
4939 fn size_hint(&self) -> (usize, Option<usize>) {
4940 self.inner.size_hint()
4944 #[stable(feature = "iter_once", since = "1.2.0")]
4945 impl<T> DoubleEndedIterator for Once<T> {
4946 fn next_back(&mut self) -> Option<T> {
4947 self.inner.next_back()
4951 #[stable(feature = "iter_once", since = "1.2.0")]
4952 impl<T> ExactSizeIterator for Once<T> {
4953 fn len(&self) -> usize {
4958 /// Creates an iterator that yields an element exactly once.
4960 /// This is commonly used to adapt a single value into a [`chain()`] of other
4961 /// kinds of iteration. Maybe you have an iterator that covers almost
4962 /// everything, but you need an extra special case. Maybe you have a function
4963 /// which works on iterators, but you only need to process one value.
4965 /// [`chain()`]: trait.Iterator.html#method.chain
4974 /// // one is the loneliest number
4975 /// let mut one = iter::once(1);
4977 /// assert_eq!(Some(1), one.next());
4979 /// // just one, that's all we get
4980 /// assert_eq!(None, one.next());
4983 /// Chaining together with another iterator. Let's say that we want to iterate
4984 /// over each file of the `.foo` directory, but also a configuration file,
4990 /// use std::path::PathBuf;
4992 /// let dirs = fs::read_dir(".foo").unwrap();
4994 /// // we need to convert from an iterator of DirEntry-s to an iterator of
4995 /// // PathBufs, so we use map
4996 /// let dirs = dirs.map(|file| file.unwrap().path());
4998 /// // now, our iterator just for our config file
4999 /// let config = iter::once(PathBuf::from(".foorc"));
5001 /// // chain the two iterators together into one big iterator
5002 /// let files = dirs.chain(config);
5004 /// // this will give us all of the files in .foo as well as .foorc
5005 /// for f in files {
5006 /// println!("{:?}", f);
5009 #[stable(feature = "iter_once", since = "1.2.0")]
5010 pub fn once<T>(value: T) -> Once<T> {
5011 Once { inner: Some(value).into_iter() }