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`]: ../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 values.into_iter() {
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
;
308 use num
::{Zero, One}
;
309 use ops
::{self, Add, Sub, FnMut, Mul, RangeFrom}
;
310 use option
::Option
::{self, Some, None}
;
314 fn _assert_is_object_safe(_
: &Iterator
<Item
=()>) {}
316 /// An interface for dealing with iterators.
318 /// This is the main iterator trait. For more about the concept of iterators
319 /// generally, please see the [module-level documentation]. In particular, you
320 /// may want to know how to [implement `Iterator`][impl].
322 /// [module-level documentation]: index.html
323 /// [impl]: index.html#implementing-iterator
324 #[stable(feature = "rust1", since = "1.0.0")]
325 #[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \
326 `.iter()` or a similar method"]
328 /// The type of the elements being iterated over.
329 #[stable(feature = "rust1", since = "1.0.0")]
332 /// Advances the iterator and returns the next value.
334 /// Returns `None` when iteration is finished. Individual iterator
335 /// implementations may choose to resume iteration, and so calling `next()`
336 /// again may or may not eventually start returning `Some(Item)` again at some
344 /// let a = [1, 2, 3];
346 /// let mut iter = a.iter();
348 /// // A call to next() returns the next value...
349 /// assert_eq!(Some(&1), iter.next());
350 /// assert_eq!(Some(&2), iter.next());
351 /// assert_eq!(Some(&3), iter.next());
353 /// // ... and then None once it's over.
354 /// assert_eq!(None, iter.next());
356 /// // More calls may or may not return None. Here, they always will.
357 /// assert_eq!(None, iter.next());
358 /// assert_eq!(None, iter.next());
360 #[stable(feature = "rust1", since = "1.0.0")]
361 fn next(&mut self) -> Option
<Self::Item
>;
363 /// Returns the bounds on the remaining length of the iterator.
365 /// Specifically, `size_hint()` returns a tuple where the first element
366 /// is the lower bound, and the second element is the upper bound.
368 /// The second half of the tuple that is returned is an `Option<usize>`. A
369 /// `None` here means that either there is no known upper bound, or the
370 /// upper bound is larger than `usize`.
372 /// # Implementation notes
374 /// It is not enforced that an iterator implementation yields the declared
375 /// number of elements. A buggy iterator may yield less than the lower bound
376 /// or more than the upper bound of elements.
378 /// `size_hint()` is primarily intended to be used for optimizations such as
379 /// reserving space for the elements of the iterator, but must not be
380 /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
381 /// implementation of `size_hint()` should not lead to memory safety
384 /// That said, the implementation should provide a correct estimation,
385 /// because otherwise it would be a violation of the trait's protocol.
387 /// The default implementation returns `(0, None)` which is correct for any
395 /// let a = [1, 2, 3];
396 /// let iter = a.iter();
398 /// assert_eq!((3, Some(3)), iter.size_hint());
401 /// A more complex example:
404 /// // The even numbers from zero to ten.
405 /// let iter = (0..10).filter(|x| x % 2 == 0);
407 /// // We might iterate from zero to ten times. Knowing that it's five
408 /// // exactly wouldn't be possible without executing filter().
409 /// assert_eq!((0, Some(10)), iter.size_hint());
411 /// // Let's add one five more numbers with chain()
412 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
414 /// // now both bounds are increased by five
415 /// assert_eq!((5, Some(15)), iter.size_hint());
418 /// Returning `None` for an upper bound:
421 /// // an infinite iterator has no upper bound
424 /// assert_eq!((0, None), iter.size_hint());
427 #[stable(feature = "rust1", since = "1.0.0")]
428 fn size_hint(&self) -> (usize, Option
<usize>) { (0, None) }
430 /// Consumes the iterator, counting the number of iterations and returning it.
432 /// This method will evaluate the iterator until its [`next()`] returns
433 /// `None`. Once `None` is encountered, `count()` returns the number of
434 /// times it called [`next()`].
436 /// [`next()`]: #method.next
438 /// # Overflow Behavior
440 /// The method does no guarding against overflows, so counting elements of
441 /// an iterator with more than `usize::MAX` elements either produces the
442 /// wrong result or panics. If debug assertions are enabled, a panic is
447 /// This function might panic if the iterator has more than `usize::MAX`
455 /// let a = [1, 2, 3];
456 /// assert_eq!(a.iter().count(), 3);
458 /// let a = [1, 2, 3, 4, 5];
459 /// assert_eq!(a.iter().count(), 5);
462 #[stable(feature = "rust1", since = "1.0.0")]
463 fn count(self) -> usize where Self: Sized
{
465 self.fold(0, |cnt
, _
| cnt
+ 1)
468 /// Consumes the iterator, returning the last element.
470 /// This method will evaluate the iterator until it returns `None`. While
471 /// doing so, it keeps track of the current element. After `None` is
472 /// returned, `last()` will then return the last element it saw.
479 /// let a = [1, 2, 3];
480 /// assert_eq!(a.iter().last(), Some(&3));
482 /// let a = [1, 2, 3, 4, 5];
483 /// assert_eq!(a.iter().last(), Some(&5));
486 #[stable(feature = "rust1", since = "1.0.0")]
487 fn last(self) -> Option
<Self::Item
> where Self: Sized
{
489 for x
in self { last = Some(x); }
493 /// Consumes the `n` first elements of the iterator, then returns the
496 /// This method will evaluate the iterator `n` times, discarding those elements.
497 /// After it does so, it will call [`next()`] and return its value.
499 /// [`next()`]: #method.next
501 /// Like most indexing operations, the count starts from zero, so `nth(0)`
502 /// returns the first value, `nth(1)` the second, and so on.
504 /// `nth()` will return `None` if `n` is larger than the length of the
512 /// let a = [1, 2, 3];
513 /// assert_eq!(a.iter().nth(1), Some(&2));
516 /// Calling `nth()` multiple times doesn't rewind the iterator:
519 /// let a = [1, 2, 3];
521 /// let mut iter = a.iter();
523 /// assert_eq!(iter.nth(1), Some(&2));
524 /// assert_eq!(iter.nth(1), None);
527 /// Returning `None` if there are less than `n` elements:
530 /// let a = [1, 2, 3];
531 /// assert_eq!(a.iter().nth(10), None);
534 #[stable(feature = "rust1", since = "1.0.0")]
535 fn nth(&mut self, mut n
: usize) -> Option
<Self::Item
> where Self: Sized
{
537 if n
== 0 { return Some(x) }
543 /// Takes two iterators and creates a new iterator over both in sequence.
545 /// `chain()` will return a new iterator which will first iterate over
546 /// values from the first iterator and then over values from the second
549 /// In other words, it links two iterators together, in a chain. 🔗
556 /// let a1 = [1, 2, 3];
557 /// let a2 = [4, 5, 6];
559 /// let mut iter = a1.iter().chain(a2.iter());
561 /// assert_eq!(iter.next(), Some(&1));
562 /// assert_eq!(iter.next(), Some(&2));
563 /// assert_eq!(iter.next(), Some(&3));
564 /// assert_eq!(iter.next(), Some(&4));
565 /// assert_eq!(iter.next(), Some(&5));
566 /// assert_eq!(iter.next(), Some(&6));
567 /// assert_eq!(iter.next(), None);
570 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
571 /// anything that can be converted into an [`Iterator`], not just an
572 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
573 /// [`IntoIterator`], and so can be passed to `chain()` directly:
575 /// [`IntoIterator`]: trait.IntoIterator.html
576 /// [`Iterator`]: trait.Iterator.html
579 /// let s1 = &[1, 2, 3];
580 /// let s2 = &[4, 5, 6];
582 /// let mut iter = s1.iter().chain(s2);
584 /// assert_eq!(iter.next(), Some(&1));
585 /// assert_eq!(iter.next(), Some(&2));
586 /// assert_eq!(iter.next(), Some(&3));
587 /// assert_eq!(iter.next(), Some(&4));
588 /// assert_eq!(iter.next(), Some(&5));
589 /// assert_eq!(iter.next(), Some(&6));
590 /// assert_eq!(iter.next(), None);
593 #[stable(feature = "rust1", since = "1.0.0")]
594 fn chain
<U
>(self, other
: U
) -> Chain
<Self, U
::IntoIter
> where
595 Self: Sized
, U
: IntoIterator
<Item
=Self::Item
>,
597 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
600 /// 'Zips up' two iterators into a single iterator of pairs.
602 /// `zip()` returns a new iterator that will iterate over two other
603 /// iterators, returning a tuple where the first element comes from the
604 /// first iterator, and the second element comes from the second iterator.
606 /// In other words, it zips two iterators together, into a single one.
608 /// When either iterator returns `None`, all further calls to `next()`
609 /// will return `None`.
616 /// let a1 = [1, 2, 3];
617 /// let a2 = [4, 5, 6];
619 /// let mut iter = a1.iter().zip(a2.iter());
621 /// assert_eq!(iter.next(), Some((&1, &4)));
622 /// assert_eq!(iter.next(), Some((&2, &5)));
623 /// assert_eq!(iter.next(), Some((&3, &6)));
624 /// assert_eq!(iter.next(), None);
627 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
628 /// anything that can be converted into an [`Iterator`], not just an
629 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
630 /// [`IntoIterator`], and so can be passed to `zip()` directly:
632 /// [`IntoIterator`]: trait.IntoIterator.html
633 /// [`Iterator`]: trait.Iterator.html
636 /// let s1 = &[1, 2, 3];
637 /// let s2 = &[4, 5, 6];
639 /// let mut iter = s1.iter().zip(s2);
641 /// assert_eq!(iter.next(), Some((&1, &4)));
642 /// assert_eq!(iter.next(), Some((&2, &5)));
643 /// assert_eq!(iter.next(), Some((&3, &6)));
644 /// assert_eq!(iter.next(), None);
647 /// `zip()` is often used to zip an infinite iterator to a finite one.
648 /// This works because the finite iterator will eventually return `None`,
649 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]:
652 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
654 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
656 /// assert_eq!((0, 'f'), enumerate[0]);
657 /// assert_eq!((0, 'f'), zipper[0]);
659 /// assert_eq!((1, 'o'), enumerate[1]);
660 /// assert_eq!((1, 'o'), zipper[1]);
662 /// assert_eq!((2, 'o'), enumerate[2]);
663 /// assert_eq!((2, 'o'), zipper[2]);
666 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
668 #[stable(feature = "rust1", since = "1.0.0")]
669 fn zip
<U
>(self, other
: U
) -> Zip
<Self, U
::IntoIter
> where
670 Self: Sized
, U
: IntoIterator
672 Zip{a: self, b: other.into_iter()}
675 /// Takes a closure and creates an iterator which calls that closure on each
678 /// `map()` transforms one iterator into another, by means of its argument:
679 /// something that implements `FnMut`. It produces a new iterator which
680 /// calls this closure on each element of the original iterator.
682 /// If you are good at thinking in types, you can think of `map()` like this:
683 /// If you have an iterator that gives you elements of some type `A`, and
684 /// you want an iterator of some other type `B`, you can use `map()`,
685 /// passing a closure that takes an `A` and returns a `B`.
687 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
688 /// lazy, it is best used when you're already working with other iterators.
689 /// If you're doing some sort of looping for a side effect, it's considered
690 /// more idiomatic to use [`for`] than `map()`.
692 /// [`for`]: ../../book/loops.html#for
699 /// let a = [1, 2, 3];
701 /// let mut iter = a.into_iter().map(|x| 2 * x);
703 /// assert_eq!(iter.next(), Some(2));
704 /// assert_eq!(iter.next(), Some(4));
705 /// assert_eq!(iter.next(), Some(6));
706 /// assert_eq!(iter.next(), None);
709 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
712 /// # #![allow(unused_must_use)]
713 /// // don't do this:
714 /// (0..5).map(|x| println!("{}", x));
716 /// // it won't even execute, as it is lazy. Rust will warn you about this.
718 /// // Instead, use for:
720 /// println!("{}", x);
724 #[stable(feature = "rust1", since = "1.0.0")]
725 fn map
<B
, F
>(self, f
: F
) -> Map
<Self, F
> where
726 Self: Sized
, F
: FnMut(Self::Item
) -> B
,
728 Map{iter: self, f: f}
731 /// Creates an iterator which uses a closure to determine if an element
732 /// should be yielded.
734 /// The closure must return `true` or `false`. `filter()` creates an
735 /// iterator which calls this closure on each element. If the closure
736 /// returns `true`, then the element is returned. If the closure returns
737 /// `false`, it will try again, and call the closure on the next element,
738 /// seeing if it passes the test.
745 /// let a = [0i32, 1, 2];
747 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
749 /// assert_eq!(iter.next(), Some(&1));
750 /// assert_eq!(iter.next(), Some(&2));
751 /// assert_eq!(iter.next(), None);
754 /// Because the closure passed to `filter()` takes a reference, and many
755 /// iterators iterate over references, this leads to a possibly confusing
756 /// situation, where the type of the closure is a double reference:
759 /// let a = [0, 1, 2];
761 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
763 /// assert_eq!(iter.next(), Some(&2));
764 /// assert_eq!(iter.next(), None);
767 /// It's common to instead use destructuring on the argument to strip away
771 /// let a = [0, 1, 2];
773 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
775 /// assert_eq!(iter.next(), Some(&2));
776 /// assert_eq!(iter.next(), None);
782 /// let a = [0, 1, 2];
784 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
786 /// assert_eq!(iter.next(), Some(&2));
787 /// assert_eq!(iter.next(), None);
792 #[stable(feature = "rust1", since = "1.0.0")]
793 fn filter
<P
>(self, predicate
: P
) -> Filter
<Self, P
> where
794 Self: Sized
, P
: FnMut(&Self::Item
) -> bool
,
796 Filter{iter: self, predicate: predicate}
799 /// Creates an iterator that both filters and maps.
801 /// The closure must return an [`Option<T>`]. `filter_map()` creates an
802 /// iterator which calls this closure on each element. If the closure
803 /// returns `Some(element)`, then that element is returned. If the
804 /// closure returns `None`, it will try again, and call the closure on the
805 /// next element, seeing if it will return `Some`.
807 /// [`Option<T>`]: ../option/enum.Option.html
809 /// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this
812 /// [`filter()`]: #method.filter
813 /// [`map()`]: #method.map
815 /// > If the closure returns `Some(element)`, then that element is returned.
817 /// In other words, it removes the [`Option<T>`] layer automatically. If your
818 /// mapping is already returning an [`Option<T>`] and you want to skip over
819 /// `None`s, then `filter_map()` is much, much nicer to use.
826 /// let a = ["1", "2", "lol"];
828 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
830 /// assert_eq!(iter.next(), Some(1));
831 /// assert_eq!(iter.next(), Some(2));
832 /// assert_eq!(iter.next(), None);
835 /// Here's the same example, but with [`filter()`] and [`map()`]:
838 /// let a = ["1", "2", "lol"];
840 /// let mut iter = a.iter()
841 /// .map(|s| s.parse().ok())
842 /// .filter(|s| s.is_some());
844 /// assert_eq!(iter.next(), Some(Some(1)));
845 /// assert_eq!(iter.next(), Some(Some(2)));
846 /// assert_eq!(iter.next(), None);
849 /// There's an extra layer of `Some` in there.
851 #[stable(feature = "rust1", since = "1.0.0")]
852 fn filter_map
<B
, F
>(self, f
: F
) -> FilterMap
<Self, F
> where
853 Self: Sized
, F
: FnMut(Self::Item
) -> Option
<B
>,
855 FilterMap { iter: self, f: f }
858 /// Creates an iterator which gives the current iteration count as well as
861 /// The iterator returned yields pairs `(i, val)`, where `i` is the
862 /// current index of iteration and `val` is the value returned by the
865 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
866 /// different sized integer, the [`zip()`] function provides similar
869 /// [`usize`]: ../primitive.usize.html
870 /// [`zip()`]: #method.zip
872 /// # Overflow Behavior
874 /// The method does no guarding against overflows, so enumerating more than
875 /// [`usize::MAX`] elements either produces the wrong result or panics. If
876 /// debug assertions are enabled, a panic is guaranteed.
878 /// [`usize::MAX`]: ../usize/constant.MAX.html
882 /// The returned iterator might panic if the to-be-returned index would
883 /// overflow a `usize`.
888 /// let a = [1, 2, 3];
890 /// let mut iter = a.iter().enumerate();
892 /// assert_eq!(iter.next(), Some((0, &1)));
893 /// assert_eq!(iter.next(), Some((1, &2)));
894 /// assert_eq!(iter.next(), Some((2, &3)));
895 /// assert_eq!(iter.next(), None);
898 #[stable(feature = "rust1", since = "1.0.0")]
899 fn enumerate(self) -> Enumerate
<Self> where Self: Sized
{
900 Enumerate { iter: self, count: 0 }
903 /// Creates an iterator which can look at the `next()` element without
906 /// Adds a [`peek()`] method to an iterator. See its documentation for
907 /// more information.
909 /// [`peek()`]: struct.Peekable.html#method.peek
916 /// let xs = [1, 2, 3];
918 /// let mut iter = xs.iter().peekable();
920 /// // peek() lets us see into the future
921 /// assert_eq!(iter.peek(), Some(&&1));
922 /// assert_eq!(iter.next(), Some(&1));
924 /// assert_eq!(iter.next(), Some(&2));
926 /// // we can peek() multiple times, the iterator won't advance
927 /// assert_eq!(iter.peek(), Some(&&3));
928 /// assert_eq!(iter.peek(), Some(&&3));
930 /// assert_eq!(iter.next(), Some(&3));
932 /// // after the iterator is finished, so is peek()
933 /// assert_eq!(iter.peek(), None);
934 /// assert_eq!(iter.next(), None);
937 #[stable(feature = "rust1", since = "1.0.0")]
938 fn peekable(self) -> Peekable
<Self> where Self: Sized
{
939 Peekable{iter: self, peeked: None}
942 /// Creates an iterator that [`skip()`]s elements based on a predicate.
944 /// [`skip()`]: #method.skip
946 /// `skip_while()` takes a closure as an argument. It will call this
947 /// closure on each element of the iterator, and ignore elements
948 /// until it returns `false`.
950 /// After `false` is returned, `skip_while()`'s job is over, and the
951 /// rest of the elements are yielded.
958 /// let a = [-1i32, 0, 1];
960 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
962 /// assert_eq!(iter.next(), Some(&0));
963 /// assert_eq!(iter.next(), Some(&1));
964 /// assert_eq!(iter.next(), None);
967 /// Because the closure passed to `skip_while()` takes a reference, and many
968 /// iterators iterate over references, this leads to a possibly confusing
969 /// situation, where the type of the closure is a double reference:
972 /// let a = [-1, 0, 1];
974 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
976 /// assert_eq!(iter.next(), Some(&0));
977 /// assert_eq!(iter.next(), Some(&1));
978 /// assert_eq!(iter.next(), None);
981 /// Stopping after an initial `false`:
984 /// let a = [-1, 0, 1, -2];
986 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
988 /// assert_eq!(iter.next(), Some(&0));
989 /// assert_eq!(iter.next(), Some(&1));
991 /// // while this would have been false, since we already got a false,
992 /// // skip_while() isn't used any more
993 /// assert_eq!(iter.next(), Some(&-2));
995 /// assert_eq!(iter.next(), None);
998 #[stable(feature = "rust1", since = "1.0.0")]
999 fn skip_while
<P
>(self, predicate
: P
) -> SkipWhile
<Self, P
> where
1000 Self: Sized
, P
: FnMut(&Self::Item
) -> bool
,
1002 SkipWhile{iter: self, flag: false, predicate: predicate}
1005 /// Creates an iterator that yields elements based on a predicate.
1007 /// `take_while()` takes a closure as an argument. It will call this
1008 /// closure on each element of the iterator, and yield elements
1009 /// while it returns `true`.
1011 /// After `false` is returned, `take_while()`'s job is over, and the
1012 /// rest of the elements are ignored.
1019 /// let a = [-1i32, 0, 1];
1021 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
1023 /// assert_eq!(iter.next(), Some(&-1));
1024 /// assert_eq!(iter.next(), None);
1027 /// Because the closure passed to `take_while()` takes a reference, and many
1028 /// iterators iterate over references, this leads to a possibly confusing
1029 /// situation, where the type of the closure is a double reference:
1032 /// let a = [-1, 0, 1];
1034 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
1036 /// assert_eq!(iter.next(), Some(&-1));
1037 /// assert_eq!(iter.next(), None);
1040 /// Stopping after an initial `false`:
1043 /// let a = [-1, 0, 1, -2];
1045 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
1047 /// assert_eq!(iter.next(), Some(&-1));
1049 /// // We have more elements that are less than zero, but since we already
1050 /// // got a false, take_while() isn't used any more
1051 /// assert_eq!(iter.next(), None);
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 fn take_while
<P
>(self, predicate
: P
) -> TakeWhile
<Self, P
> where
1056 Self: Sized
, P
: FnMut(&Self::Item
) -> bool
,
1058 TakeWhile{iter: self, flag: false, predicate: predicate}
1061 /// Creates an iterator that skips the first `n` elements.
1063 /// After they have been consumed, the rest of the elements are yielded.
1070 /// let a = [1, 2, 3];
1072 /// let mut iter = a.iter().skip(2);
1074 /// assert_eq!(iter.next(), Some(&3));
1075 /// assert_eq!(iter.next(), None);
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 fn skip(self, n
: usize) -> Skip
<Self> where Self: Sized
{
1080 Skip{iter: self, n: n}
1083 /// Creates an iterator that yields its first `n` elements.
1090 /// let a = [1, 2, 3];
1092 /// let mut iter = a.iter().take(2);
1094 /// assert_eq!(iter.next(), Some(&1));
1095 /// assert_eq!(iter.next(), Some(&2));
1096 /// assert_eq!(iter.next(), None);
1099 /// `take()` is often used with an infinite iterator, to make it finite:
1102 /// let mut iter = (0..).take(3);
1104 /// assert_eq!(iter.next(), Some(0));
1105 /// assert_eq!(iter.next(), Some(1));
1106 /// assert_eq!(iter.next(), Some(2));
1107 /// assert_eq!(iter.next(), None);
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 fn take(self, n
: usize) -> Take
<Self> where Self: Sized
, {
1112 Take{iter: self, n: n}
1115 /// An iterator adaptor similar to [`fold()`] that holds internal state and
1116 /// produces a new iterator.
1118 /// [`fold()`]: #method.fold
1120 /// `scan()` takes two arguments: an initial value which seeds the internal
1121 /// state, and a closure with two arguments, the first being a mutable
1122 /// reference to the internal state and the second an iterator element.
1123 /// The closure can assign to the internal state to share state between
1126 /// On iteration, the closure will be applied to each element of the
1127 /// iterator and the return value from the closure, an [`Option`], is
1128 /// yielded by the iterator.
1130 /// [`Option`]: ../option/enum.Option.html
1137 /// let a = [1, 2, 3];
1139 /// let mut iter = a.iter().scan(1, |state, &x| {
1140 /// // each iteration, we'll multiply the state by the element
1141 /// *state = *state * x;
1143 /// // the value passed on to the next iteration
1147 /// assert_eq!(iter.next(), Some(1));
1148 /// assert_eq!(iter.next(), Some(2));
1149 /// assert_eq!(iter.next(), Some(6));
1150 /// assert_eq!(iter.next(), None);
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 fn scan
<St
, B
, F
>(self, initial_state
: St
, f
: F
) -> Scan
<Self, St
, F
>
1155 where Self: Sized
, F
: FnMut(&mut St
, Self::Item
) -> Option
<B
>,
1157 Scan{iter: self, f: f, state: initial_state}
1160 /// Creates an iterator that works like map, but flattens nested structure.
1162 /// The [`map()`] adapter is very useful, but only when the closure
1163 /// argument produces values. If it produces an iterator instead, there's
1164 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1167 /// [`map()`]: #method.map
1169 /// Another way of thinking about `flat_map()`: [`map()`]'s closure returns
1170 /// one item for each element, and `flat_map()`'s closure returns an
1171 /// iterator for each element.
1178 /// let words = ["alpha", "beta", "gamma"];
1180 /// // chars() returns an iterator
1181 /// let merged: String = words.iter()
1182 /// .flat_map(|s| s.chars())
1184 /// assert_eq!(merged, "alphabetagamma");
1187 #[stable(feature = "rust1", since = "1.0.0")]
1188 fn flat_map
<U
, F
>(self, f
: F
) -> FlatMap
<Self, U
, F
>
1189 where Self: Sized
, U
: IntoIterator
, F
: FnMut(Self::Item
) -> U
,
1191 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
1194 /// Creates an iterator which ends after the first `None`.
1196 /// After an iterator returns `None`, future calls may or may not yield
1197 /// `Some(T)` again. `fuse()` adapts an iterator, ensuring that after a
1198 /// `None` is given, it will always return `None` forever.
1205 /// // an iterator which alternates between Some and None
1206 /// struct Alternate {
1210 /// impl Iterator for Alternate {
1211 /// type Item = i32;
1213 /// fn next(&mut self) -> Option<i32> {
1214 /// let val = self.state;
1215 /// self.state = self.state + 1;
1217 /// // if it's even, Some(i32), else None
1218 /// if val % 2 == 0 {
1226 /// let mut iter = Alternate { state: 0 };
1228 /// // we can see our iterator going back and forth
1229 /// assert_eq!(iter.next(), Some(0));
1230 /// assert_eq!(iter.next(), None);
1231 /// assert_eq!(iter.next(), Some(2));
1232 /// assert_eq!(iter.next(), None);
1234 /// // however, once we fuse it...
1235 /// let mut iter = iter.fuse();
1237 /// assert_eq!(iter.next(), Some(4));
1238 /// assert_eq!(iter.next(), None);
1240 /// // it will always return None after the first time.
1241 /// assert_eq!(iter.next(), None);
1242 /// assert_eq!(iter.next(), None);
1243 /// assert_eq!(iter.next(), None);
1246 #[stable(feature = "rust1", since = "1.0.0")]
1247 fn fuse(self) -> Fuse
<Self> where Self: Sized
{
1248 Fuse{iter: self, done: false}
1251 /// Do something with each element of an iterator, passing the value on.
1253 /// When using iterators, you'll often chain several of them together.
1254 /// While working on such code, you might want to check out what's
1255 /// happening at various parts in the pipeline. To do that, insert
1256 /// a call to `inspect()`.
1258 /// It's much more common for `inspect()` to be used as a debugging tool
1259 /// than to exist in your final code, but never say never.
1266 /// let a = [1, 4, 2, 3];
1268 /// // this iterator sequence is complex.
1269 /// let sum = a.iter()
1271 /// .filter(|&x| x % 2 == 0)
1272 /// .fold(0, |sum, i| sum + i);
1274 /// println!("{}", sum);
1276 /// // let's add some inspect() calls to investigate what's happening
1277 /// let sum = a.iter()
1279 /// .inspect(|x| println!("about to filter: {}", x))
1280 /// .filter(|&x| x % 2 == 0)
1281 /// .inspect(|x| println!("made it through filter: {}", x))
1282 /// .fold(0, |sum, i| sum + i);
1284 /// println!("{}", sum);
1287 /// This will print:
1290 /// about to filter: 1
1291 /// about to filter: 4
1292 /// made it through filter: 4
1293 /// about to filter: 2
1294 /// made it through filter: 2
1295 /// about to filter: 3
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 fn inspect
<F
>(self, f
: F
) -> Inspect
<Self, F
> where
1301 Self: Sized
, F
: FnMut(&Self::Item
),
1303 Inspect{iter: self, f: f}
1306 /// Borrows an iterator, rather than consuming it.
1308 /// This is useful to allow applying iterator adaptors while still
1309 /// retaining ownership of the original iterator.
1316 /// let a = [1, 2, 3];
1318 /// let iter = a.into_iter();
1320 /// let sum: i32 = iter.take(5)
1321 /// .fold(0, |acc, &i| acc + i );
1323 /// assert_eq!(sum, 6);
1325 /// // if we try to use iter again, it won't work. The following line
1326 /// // gives "error: use of moved value: `iter`
1327 /// // assert_eq!(iter.next(), None);
1329 /// // let's try that again
1330 /// let a = [1, 2, 3];
1332 /// let mut iter = a.into_iter();
1334 /// // instead, we add in a .by_ref()
1335 /// let sum: i32 = iter.by_ref()
1337 /// .fold(0, |acc, &i| acc + i );
1339 /// assert_eq!(sum, 3);
1341 /// // now this is just fine:
1342 /// assert_eq!(iter.next(), Some(&3));
1343 /// assert_eq!(iter.next(), None);
1345 #[stable(feature = "rust1", since = "1.0.0")]
1346 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1348 /// Transforms an iterator into a collection.
1350 /// `collect()` can take anything iterable, and turn it into a relevant
1351 /// collection. This is one of the more powerful methods in the standard
1352 /// library, used in a variety of contexts.
1354 /// The most basic pattern in which `collect()` is used is to turn one
1355 /// collection into another. You take a collection, call `iter()` on it,
1356 /// do a bunch of transformations, and then `collect()` at the end.
1358 /// One of the keys to `collect()`'s power is that many things you might
1359 /// not think of as 'collections' actually are. For example, a [`String`]
1360 /// is a collection of [`char`]s. And a collection of [`Result<T, E>`] can
1361 /// be thought of as single `Result<Collection<T>, E>`. See the examples
1364 /// [`String`]: ../string/struct.String.html
1365 /// [`Result<T, E>`]: ../result/enum.Result.html
1366 /// [`char`]: ../primitive.char.html
1368 /// Because `collect()` is so general, it can cause problems with type
1369 /// inference. As such, `collect()` is one of the few times you'll see
1370 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1371 /// helps the inference algorithm understand specifically which collection
1372 /// you're trying to collect into.
1379 /// let a = [1, 2, 3];
1381 /// let doubled: Vec<i32> = a.iter()
1382 /// .map(|&x| x * 2)
1385 /// assert_eq!(vec![2, 4, 6], doubled);
1388 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1389 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1391 /// [`VecDeque<T>`]: ../collections/struct.VecDeque.html
1394 /// use std::collections::VecDeque;
1396 /// let a = [1, 2, 3];
1398 /// let doubled: VecDeque<i32> = a.iter()
1399 /// .map(|&x| x * 2)
1402 /// assert_eq!(2, doubled[0]);
1403 /// assert_eq!(4, doubled[1]);
1404 /// assert_eq!(6, doubled[2]);
1407 /// Using the 'turbofish' instead of annotationg `doubled`:
1410 /// let a = [1, 2, 3];
1412 /// let doubled = a.iter()
1413 /// .map(|&x| x * 2)
1414 /// .collect::<Vec<i32>>();
1416 /// assert_eq!(vec![2, 4, 6], doubled);
1419 /// Because `collect()` cares about what you're collecting into, you can
1420 /// still use a partial type hint, `_`, with the turbofish:
1423 /// let a = [1, 2, 3];
1425 /// let doubled = a.iter()
1426 /// .map(|&x| x * 2)
1427 /// .collect::<Vec<_>>();
1429 /// assert_eq!(vec![2, 4, 6], doubled);
1432 /// Using `collect()` to make a [`String`]:
1435 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1437 /// let hello: String = chars.iter()
1438 /// .map(|&x| x as u8)
1439 /// .map(|x| (x + 1) as char)
1442 /// assert_eq!("hello", hello);
1445 /// If you have a list of [`Result<T, E>`]s, you can use `collect()` to
1446 /// see if any of them failed:
1449 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1451 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1453 /// // gives us the first error
1454 /// assert_eq!(Err("nope"), result);
1456 /// let results = [Ok(1), Ok(3)];
1458 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1460 /// // gives us the list of answers
1461 /// assert_eq!(Ok(vec![1, 3]), result);
1464 #[stable(feature = "rust1", since = "1.0.0")]
1465 fn collect
<B
: FromIterator
<Self::Item
>>(self) -> B
where Self: Sized
{
1466 FromIterator
::from_iter(self)
1469 /// Consumes an iterator, creating two collections from it.
1471 /// The predicate passed to `partition()` can return `true`, or `false`.
1472 /// `partition()` returns a pair, all of the elements for which it returned
1473 /// `true`, and all of the elements for which it returned `false`.
1480 /// let a = [1, 2, 3];
1482 /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1483 /// .partition(|&n| n % 2 == 0);
1485 /// assert_eq!(even, vec![2]);
1486 /// assert_eq!(odd, vec![1, 3]);
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 fn partition
<B
, F
>(self, mut f
: F
) -> (B
, B
) where
1491 B
: Default
+ Extend
<Self::Item
>,
1492 F
: FnMut(&Self::Item
) -> bool
1494 let mut left
: B
= Default
::default();
1495 let mut right
: B
= Default
::default();
1499 left
.extend(Some(x
))
1501 right
.extend(Some(x
))
1508 /// An iterator adaptor that applies a function, producing a single, final value.
1510 /// `fold()` takes two arguments: an initial value, and a closure with two
1511 /// arguments: an 'accumulator', and an element. It returns the value that
1512 /// the accumulator should have for the next iteration.
1514 /// The initial value is the value the accumulator will have on the first
1517 /// After applying this closure to every element of the iterator, `fold()`
1518 /// returns the accumulator.
1520 /// This operation is sometimes called 'reduce' or 'inject'.
1522 /// Folding is useful whenever you have a collection of something, and want
1523 /// to produce a single value from it.
1530 /// let a = [1, 2, 3];
1532 /// // the sum of all of the elements of a
1533 /// let sum = a.iter()
1534 /// .fold(0, |acc, &x| acc + x);
1536 /// assert_eq!(sum, 6);
1539 /// Let's walk through each step of the iteration here:
1541 /// | element | acc | x | result |
1542 /// |---------|-----|---|--------|
1544 /// | 1 | 0 | 1 | 1 |
1545 /// | 2 | 1 | 2 | 3 |
1546 /// | 3 | 3 | 3 | 6 |
1548 /// And so, our final result, `6`.
1550 /// It's common for people who haven't used iterators a lot to
1551 /// use a `for` loop with a list of things to build up a result. Those
1552 /// can be turned into `fold()`s:
1555 /// let numbers = [1, 2, 3, 4, 5];
1557 /// let mut result = 0;
1560 /// for i in &numbers {
1561 /// result = result + i;
1565 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1567 /// // they're the same
1568 /// assert_eq!(result, result2);
1571 #[stable(feature = "rust1", since = "1.0.0")]
1572 fn fold
<B
, F
>(self, init
: B
, mut f
: F
) -> B
where
1573 Self: Sized
, F
: FnMut(B
, Self::Item
) -> B
,
1575 let mut accum
= init
;
1577 accum
= f(accum
, x
);
1582 /// Tests if every element of the iterator matches a predicate.
1584 /// `all()` takes a closure that returns `true` or `false`. It applies
1585 /// this closure to each element of the iterator, and if they all return
1586 /// `true`, then so does `all()`. If any of them return `false`, it
1587 /// returns `false`.
1589 /// `all()` is short-circuting; in other words, it will stop processing
1590 /// as soon as it finds a `false`, given that no matter what else happens,
1591 /// the result will also be `false`.
1593 /// An empty iterator returns `true`.
1600 /// let a = [1, 2, 3];
1602 /// assert!(a.iter().all(|&x| x > 0));
1604 /// assert!(!a.iter().all(|&x| x > 2));
1607 /// Stopping at the first `false`:
1610 /// let a = [1, 2, 3];
1612 /// let mut iter = a.iter();
1614 /// assert!(!iter.all(|&x| x != 2));
1616 /// // we can still use `iter`, as there are more elements.
1617 /// assert_eq!(iter.next(), Some(&3));
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 fn all
<F
>(&mut self, mut f
: F
) -> bool
where
1622 Self: Sized
, F
: FnMut(Self::Item
) -> bool
1632 /// Tests if any element of the iterator matches a predicate.
1634 /// `any()` takes a closure that returns `true` or `false`. It applies
1635 /// this closure to each element of the iterator, and if any of them return
1636 /// `true`, then so does `any()`. If they all return `false`, it
1637 /// returns `false`.
1639 /// `any()` is short-circuting; in other words, it will stop processing
1640 /// as soon as it finds a `true`, given that no matter what else happens,
1641 /// the result will also be `true`.
1643 /// An empty iterator returns `false`.
1650 /// let a = [1, 2, 3];
1652 /// assert!(a.iter().any(|&x| x > 0));
1654 /// assert!(!a.iter().any(|&x| x > 5));
1657 /// Stopping at the first `true`:
1660 /// let a = [1, 2, 3];
1662 /// let mut iter = a.iter();
1664 /// assert!(iter.any(|&x| x != 2));
1666 /// // we can still use `iter`, as there are more elements.
1667 /// assert_eq!(iter.next(), Some(&2));
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 fn any
<F
>(&mut self, mut f
: F
) -> bool
where
1673 F
: FnMut(Self::Item
) -> bool
1683 /// Searches for an element of an iterator that satisfies a predicate.
1685 /// `find()` takes a closure that returns `true` or `false`. It applies
1686 /// this closure to each element of the iterator, and if any of them return
1687 /// `true`, then `find()` returns `Some(element)`. If they all return
1688 /// `false`, it returns `None`.
1690 /// `find()` is short-circuting; in other words, it will stop processing
1691 /// as soon as the closure returns `true`.
1693 /// Because `find()` takes a reference, and many iterators iterate over
1694 /// references, this leads to a possibly confusing situation where the
1695 /// argument is a double reference. You can see this effect in the
1696 /// examples below, with `&&x`.
1703 /// let a = [1, 2, 3];
1705 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1707 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1710 /// Stopping at the first `true`:
1713 /// let a = [1, 2, 3];
1715 /// let mut iter = a.iter();
1717 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1719 /// // we can still use `iter`, as there are more elements.
1720 /// assert_eq!(iter.next(), Some(&3));
1723 #[stable(feature = "rust1", since = "1.0.0")]
1724 fn find
<P
>(&mut self, mut predicate
: P
) -> Option
<Self::Item
> where
1726 P
: FnMut(&Self::Item
) -> bool
,
1729 if predicate(&x
) { return Some(x) }
1734 /// Searches for an element in an iterator, returning its index.
1736 /// `position()` takes a closure that returns `true` or `false`. It applies
1737 /// this closure to each element of the iterator, and if one of them
1738 /// returns `true`, then `position()` returns `Some(index)`. If all of
1739 /// them return `false`, it returns `None`.
1741 /// `position()` is short-circuting; in other words, it will stop
1742 /// processing as soon as it finds a `true`.
1744 /// # Overflow Behavior
1746 /// The method does no guarding against overflows, so if there are more
1747 /// than `usize::MAX` non-matching elements, it either produces the wrong
1748 /// result or panics. If debug assertions are enabled, a panic is
1753 /// This function might panic if the iterator has more than `usize::MAX`
1754 /// non-matching elements.
1761 /// let a = [1, 2, 3];
1763 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1765 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1768 /// Stopping at the first `true`:
1771 /// let a = [1, 2, 3];
1773 /// let mut iter = a.iter();
1775 /// assert_eq!(iter.position(|&x| x == 2), Some(1));
1777 /// // we can still use `iter`, as there are more elements.
1778 /// assert_eq!(iter.next(), Some(&3));
1781 #[stable(feature = "rust1", since = "1.0.0")]
1782 fn position
<P
>(&mut self, mut predicate
: P
) -> Option
<usize> where
1784 P
: FnMut(Self::Item
) -> bool
,
1786 // `enumerate` might overflow.
1787 for (i
, x
) in self.enumerate() {
1795 /// Searches for an element in an iterator from the right, returning its
1798 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1799 /// this closure to each element of the iterator, starting from the end,
1800 /// and if one of them returns `true`, then `rposition()` returns
1801 /// `Some(index)`. If all of them return `false`, it returns `None`.
1803 /// `rposition()` is short-circuting; in other words, it will stop
1804 /// processing as soon as it finds a `true`.
1811 /// let a = [1, 2, 3];
1813 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1815 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1818 /// Stopping at the first `true`:
1821 /// let a = [1, 2, 3];
1823 /// let mut iter = a.iter();
1825 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1827 /// // we can still use `iter`, as there are more elements.
1828 /// assert_eq!(iter.next(), Some(&1));
1831 #[stable(feature = "rust1", since = "1.0.0")]
1832 fn rposition
<P
>(&mut self, mut predicate
: P
) -> Option
<usize> where
1833 P
: FnMut(Self::Item
) -> bool
,
1834 Self: Sized
+ ExactSizeIterator
+ DoubleEndedIterator
1836 let mut i
= self.len();
1838 while let Some(v
) = self.next_back() {
1842 // No need for an overflow check here, because `ExactSizeIterator`
1843 // implies that the number of elements fits into a `usize`.
1849 /// Returns the maximum element of an iterator.
1851 /// If the two elements are equally maximum, the latest element is
1859 /// let a = [1, 2, 3];
1861 /// assert_eq!(a.iter().max(), Some(&3));
1864 #[stable(feature = "rust1", since = "1.0.0")]
1865 fn max(self) -> Option
<Self::Item
> where Self: Sized
, Self::Item
: Ord
1869 // switch to y even if it is only equal, to preserve
1871 |_
, x
, _
, y
| *x
<= *y
)
1875 /// Returns the minimum element of an iterator.
1877 /// If the two elements are equally minimum, the first element is
1885 /// let a = [1, 2, 3];
1887 /// assert_eq!(a.iter().min(), Some(&1));
1890 #[stable(feature = "rust1", since = "1.0.0")]
1891 fn min(self) -> Option
<Self::Item
> where Self: Sized
, Self::Item
: Ord
1895 // only switch to y if it is strictly smaller, to
1896 // preserve stability.
1897 |_
, x
, _
, y
| *x
> *y
)
1901 #[allow(missing_docs)]
1903 #[unstable(feature = "iter_cmp",
1904 reason
= "may want to produce an Ordering directly; see #15311",
1906 #[rustc_deprecated(reason = "renamed to max_by_key", since = "1.6.0")]
1907 fn max_by
<B
: Ord
, F
>(self, f
: F
) -> Option
<Self::Item
> where
1909 F
: FnMut(&Self::Item
) -> B
,
1914 /// Returns the element that gives the maximum value from the
1915 /// specified function.
1917 /// Returns the rightmost element if the comparison determines two elements
1918 /// to be equally maximum.
1923 /// let a = [-3_i32, 0, 1, 5, -10];
1924 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1927 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1928 fn max_by_key
<B
: Ord
, F
>(self, f
: F
) -> Option
<Self::Item
>
1929 where Self: Sized
, F
: FnMut(&Self::Item
) -> B
,
1933 // switch to y even if it is only equal, to preserve
1935 |x_p
, _
, y_p
, _
| x_p
<= y_p
)
1940 #[allow(missing_docs)]
1941 #[unstable(feature = "iter_cmp",
1942 reason
= "may want to produce an Ordering directly; see #15311",
1944 #[rustc_deprecated(reason = "renamed to min_by_key", since = "1.6.0")]
1945 fn min_by
<B
: Ord
, F
>(self, f
: F
) -> Option
<Self::Item
> where
1947 F
: FnMut(&Self::Item
) -> B
,
1952 /// Returns the element that gives the minimum value from the
1953 /// specified function.
1955 /// Returns the latest element if the comparison determines two elements
1956 /// to be equally minimum.
1961 /// let a = [-3_i32, 0, 1, 5, -10];
1962 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
1964 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1965 fn min_by_key
<B
: Ord
, F
>(self, f
: F
) -> Option
<Self::Item
>
1966 where Self: Sized
, F
: FnMut(&Self::Item
) -> B
,
1970 // only switch to y if it is strictly smaller, to
1971 // preserve stability.
1972 |x_p
, _
, y_p
, _
| x_p
> y_p
)
1976 /// Reverses an iterator's direction.
1978 /// Usually, iterators iterate from left to right. After using `rev()`,
1979 /// an iterator will instead iterate from right to left.
1981 /// This is only possible if the iterator has an end, so `rev()` only
1982 /// works on [`DoubleEndedIterator`]s.
1984 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1989 /// let a = [1, 2, 3];
1991 /// let mut iter = a.iter().rev();
1993 /// assert_eq!(iter.next(), Some(&3));
1994 /// assert_eq!(iter.next(), Some(&2));
1995 /// assert_eq!(iter.next(), Some(&1));
1997 /// assert_eq!(iter.next(), None);
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 fn rev(self) -> Rev
<Self> where Self: Sized
+ DoubleEndedIterator
{
2005 /// Converts an iterator of pairs into a pair of containers.
2007 /// `unzip()` consumes an entire iterator of pairs, producing two
2008 /// collections: one from the left elements of the pairs, and one
2009 /// from the right elements.
2011 /// This function is, in some sense, the opposite of [`zip()`].
2013 /// [`zip()`]: #method.zip
2020 /// let a = [(1, 2), (3, 4)];
2022 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2024 /// assert_eq!(left, [1, 3]);
2025 /// assert_eq!(right, [2, 4]);
2027 #[stable(feature = "rust1", since = "1.0.0")]
2028 fn unzip
<A
, B
, FromA
, FromB
>(self) -> (FromA
, FromB
) where
2029 FromA
: Default
+ Extend
<A
>,
2030 FromB
: Default
+ Extend
<B
>,
2031 Self: Sized
+ Iterator
<Item
=(A
, B
)>,
2033 struct SizeHint
<A
>(usize, Option
<usize>, marker
::PhantomData
<A
>);
2034 impl<A
> Iterator
for SizeHint
<A
> {
2037 fn next(&mut self) -> Option
<A
> { None }
2038 fn size_hint(&self) -> (usize, Option
<usize>) {
2043 let (lo
, hi
) = self.size_hint();
2044 let mut ts
: FromA
= Default
::default();
2045 let mut us
: FromB
= Default
::default();
2047 ts
.extend(SizeHint(lo
, hi
, marker
::PhantomData
));
2048 us
.extend(SizeHint(lo
, hi
, marker
::PhantomData
));
2050 for (t
, u
) in self {
2058 /// Creates an iterator which clone()s all of its elements.
2060 /// This is useful when you have an iterator over `&T`, but you need an
2061 /// iterator over `T`.
2068 /// let a = [1, 2, 3];
2070 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2072 /// // cloned is the same as .map(|&x| x), for integers
2073 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2075 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2076 /// assert_eq!(v_map, vec![1, 2, 3]);
2078 #[stable(feature = "rust1", since = "1.0.0")]
2079 fn cloned
<'a
, T
: 'a
>(self) -> Cloned
<Self>
2080 where Self: Sized
+ Iterator
<Item
=&'a T
>, T
: Clone
2085 /// Repeats an iterator endlessly.
2087 /// Instead of stopping at `None`, the iterator will instead start again,
2088 /// from the beginning. After iterating again, it will start at the
2089 /// beginning again. And again. And again. Forever.
2096 /// let a = [1, 2, 3];
2098 /// let mut it = a.iter().cycle();
2100 /// assert_eq!(it.next(), Some(&1));
2101 /// assert_eq!(it.next(), Some(&2));
2102 /// assert_eq!(it.next(), Some(&3));
2103 /// assert_eq!(it.next(), Some(&1));
2104 /// assert_eq!(it.next(), Some(&2));
2105 /// assert_eq!(it.next(), Some(&3));
2106 /// assert_eq!(it.next(), Some(&1));
2108 #[stable(feature = "rust1", since = "1.0.0")]
2110 fn cycle(self) -> Cycle
<Self> where Self: Sized
+ Clone
{
2111 Cycle{orig: self.clone(), iter: self}
2114 /// Sums the elements of an iterator.
2116 /// Takes each element, adds them together, and returns the result.
2118 /// An empty iterator returns the zero value of the type.
2125 /// #![feature(iter_arith)]
2127 /// let a = [1, 2, 3];
2128 /// let sum: i32 = a.iter().sum();
2130 /// assert_eq!(sum, 6);
2132 #[unstable(feature = "iter_arith", reason = "bounds recently changed",
2134 fn sum
<S
>(self) -> S
where
2135 S
: Add
<Self::Item
, Output
=S
> + Zero
,
2138 self.fold(Zero
::zero(), |s
, e
| s
+ e
)
2141 /// Iterates over the entire iterator, multiplying all the elements
2143 /// An empty iterator returns the one value of the type.
2148 /// #![feature(iter_arith)]
2150 /// fn factorial(n: u32) -> u32 {
2151 /// (1..).take_while(|&i| i <= n).product()
2153 /// assert_eq!(factorial(0), 1);
2154 /// assert_eq!(factorial(1), 1);
2155 /// assert_eq!(factorial(5), 120);
2157 #[unstable(feature="iter_arith", reason = "bounds recently changed",
2159 fn product
<P
>(self) -> P
where
2160 P
: Mul
<Self::Item
, Output
=P
> + One
,
2163 self.fold(One
::one(), |p
, e
| p
* e
)
2166 /// Lexicographically compares the elements of this `Iterator` with those
2168 #[stable(feature = "iter_order", since = "1.5.0")]
2169 fn cmp
<I
>(mut self, other
: I
) -> Ordering
where
2170 I
: IntoIterator
<Item
= Self::Item
>,
2174 let mut other
= other
.into_iter();
2177 match (self.next(), other
.next()) {
2178 (None
, None
) => return Ordering
::Equal
,
2179 (None
, _
) => return Ordering
::Less
,
2180 (_
, None
) => return Ordering
::Greater
,
2181 (Some(x
), Some(y
)) => match x
.cmp(&y
) {
2182 Ordering
::Equal
=> (),
2183 non_eq
=> return non_eq
,
2189 /// Lexicographically compares the elements of this `Iterator` with those
2191 #[stable(feature = "iter_order", since = "1.5.0")]
2192 fn partial_cmp
<I
>(mut self, other
: I
) -> Option
<Ordering
> where
2194 Self::Item
: PartialOrd
<I
::Item
>,
2197 let mut other
= other
.into_iter();
2200 match (self.next(), other
.next()) {
2201 (None
, None
) => return Some(Ordering
::Equal
),
2202 (None
, _
) => return Some(Ordering
::Less
),
2203 (_
, None
) => return Some(Ordering
::Greater
),
2204 (Some(x
), Some(y
)) => match x
.partial_cmp(&y
) {
2205 Some(Ordering
::Equal
) => (),
2206 non_eq
=> return non_eq
,
2212 /// Determines if the elements of this `Iterator` are equal to those of
2214 #[stable(feature = "iter_order", since = "1.5.0")]
2215 fn eq
<I
>(mut self, other
: I
) -> bool
where
2217 Self::Item
: PartialEq
<I
::Item
>,
2220 let mut other
= other
.into_iter();
2223 match (self.next(), other
.next()) {
2224 (None
, None
) => return true,
2225 (None
, _
) | (_
, None
) => return false,
2226 (Some(x
), Some(y
)) => if x
!= y { return false }
,
2231 /// Determines if the elements of this `Iterator` are unequal to those of
2233 #[stable(feature = "iter_order", since = "1.5.0")]
2234 fn ne
<I
>(mut self, other
: I
) -> bool
where
2236 Self::Item
: PartialEq
<I
::Item
>,
2239 let mut other
= other
.into_iter();
2242 match (self.next(), other
.next()) {
2243 (None
, None
) => return false,
2244 (None
, _
) | (_
, None
) => return true,
2245 (Some(x
), Some(y
)) => if x
.ne(&y
) { return true }
,
2250 /// Determines if the elements of this `Iterator` are lexicographically
2251 /// less than those of another.
2252 #[stable(feature = "iter_order", since = "1.5.0")]
2253 fn lt
<I
>(mut self, other
: I
) -> bool
where
2255 Self::Item
: PartialOrd
<I
::Item
>,
2258 let mut other
= other
.into_iter();
2261 match (self.next(), other
.next()) {
2262 (None
, None
) => return false,
2263 (None
, _
) => return true,
2264 (_
, None
) => return false,
2265 (Some(x
), Some(y
)) => {
2266 match x
.partial_cmp(&y
) {
2267 Some(Ordering
::Less
) => return true,
2268 Some(Ordering
::Equal
) => {}
2269 Some(Ordering
::Greater
) => return false,
2270 None
=> return false,
2277 /// Determines if the elements of this `Iterator` are lexicographically
2278 /// less or equal to those of another.
2279 #[stable(feature = "iter_order", since = "1.5.0")]
2280 fn le
<I
>(mut self, other
: I
) -> bool
where
2282 Self::Item
: PartialOrd
<I
::Item
>,
2285 let mut other
= other
.into_iter();
2288 match (self.next(), other
.next()) {
2289 (None
, None
) => return true,
2290 (None
, _
) => return true,
2291 (_
, None
) => return false,
2292 (Some(x
), Some(y
)) => {
2293 match x
.partial_cmp(&y
) {
2294 Some(Ordering
::Less
) => return true,
2295 Some(Ordering
::Equal
) => {}
2296 Some(Ordering
::Greater
) => return false,
2297 None
=> return false,
2304 /// Determines if the elements of this `Iterator` are lexicographically
2305 /// greater than those of another.
2306 #[stable(feature = "iter_order", since = "1.5.0")]
2307 fn gt
<I
>(mut self, other
: I
) -> bool
where
2309 Self::Item
: PartialOrd
<I
::Item
>,
2312 let mut other
= other
.into_iter();
2315 match (self.next(), other
.next()) {
2316 (None
, None
) => return false,
2317 (None
, _
) => return false,
2318 (_
, None
) => return true,
2319 (Some(x
), Some(y
)) => {
2320 match x
.partial_cmp(&y
) {
2321 Some(Ordering
::Less
) => return false,
2322 Some(Ordering
::Equal
) => {}
2323 Some(Ordering
::Greater
) => return true,
2324 None
=> return false,
2331 /// Determines if the elements of this `Iterator` are lexicographically
2332 /// greater than or equal to those of another.
2333 #[stable(feature = "iter_order", since = "1.5.0")]
2334 fn ge
<I
>(mut self, other
: I
) -> bool
where
2336 Self::Item
: PartialOrd
<I
::Item
>,
2339 let mut other
= other
.into_iter();
2342 match (self.next(), other
.next()) {
2343 (None
, None
) => return true,
2344 (None
, _
) => return false,
2345 (_
, None
) => return true,
2346 (Some(x
), Some(y
)) => {
2347 match x
.partial_cmp(&y
) {
2348 Some(Ordering
::Less
) => return false,
2349 Some(Ordering
::Equal
) => {}
2350 Some(Ordering
::Greater
) => return true,
2351 None
=> return false,
2359 /// Select an element from an iterator based on the given projection
2360 /// and "comparison" function.
2362 /// This is an idiosyncratic helper to try to factor out the
2363 /// commonalities of {max,min}{,_by}. In particular, this avoids
2364 /// having to implement optimizations several times.
2366 fn select_fold1
<I
,B
, FProj
, FCmp
>(mut it
: I
,
2368 mut f_cmp
: FCmp
) -> Option
<(B
, I
::Item
)>
2370 FProj
: FnMut(&I
::Item
) -> B
,
2371 FCmp
: FnMut(&B
, &I
::Item
, &B
, &I
::Item
) -> bool
2373 // start with the first element as our selection. This avoids
2374 // having to use `Option`s inside the loop, translating to a
2375 // sizeable performance gain (6x in one case).
2376 it
.next().map(|mut sel
| {
2377 let mut sel_p
= f_proj(&sel
);
2380 let x_p
= f_proj(&x
);
2381 if f_cmp(&sel_p
, &sel
, &x_p
, &x
) {
2390 #[stable(feature = "rust1", since = "1.0.0")]
2391 impl<'a
, I
: Iterator
+ ?Sized
> Iterator
for &'a
mut I
{
2392 type Item
= I
::Item
;
2393 fn next(&mut self) -> Option
<I
::Item
> { (**self).next() }
2394 fn size_hint(&self) -> (usize, Option
<usize>) { (**self).size_hint() }
2397 /// Conversion from an `Iterator`.
2399 /// By implementing `FromIterator` for a type, you define how it will be
2400 /// created from an iterator. This is common for types which describe a
2401 /// collection of some kind.
2403 /// `FromIterator`'s [`from_iter()`] is rarely called explicitly, and is instead
2404 /// used through [`Iterator`]'s [`collect()`] method. See [`collect()`]'s
2405 /// documentation for more examples.
2407 /// [`from_iter()`]: #tymethod.from_iter
2408 /// [`Iterator`]: trait.Iterator.html
2409 /// [`collect()`]: trait.Iterator.html#method.collect
2411 /// See also: [`IntoIterator`].
2413 /// [`IntoIterator`]: trait.IntoIterator.html
2420 /// use std::iter::FromIterator;
2422 /// let five_fives = std::iter::repeat(5).take(5);
2424 /// let v = Vec::from_iter(five_fives);
2426 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2429 /// Using [`collect()`] to implicitly use `FromIterator`:
2432 /// let five_fives = std::iter::repeat(5).take(5);
2434 /// let v: Vec<i32> = five_fives.collect();
2436 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2439 /// Implementing `FromIterator` for your type:
2442 /// use std::iter::FromIterator;
2444 /// // A sample collection, that's just a wrapper over Vec<T>
2445 /// #[derive(Debug)]
2446 /// struct MyCollection(Vec<i32>);
2448 /// // Let's give it some methods so we can create one and add things
2450 /// impl MyCollection {
2451 /// fn new() -> MyCollection {
2452 /// MyCollection(Vec::new())
2455 /// fn add(&mut self, elem: i32) {
2456 /// self.0.push(elem);
2460 /// // and we'll implement FromIterator
2461 /// impl FromIterator<i32> for MyCollection {
2462 /// fn from_iter<I: IntoIterator<Item=i32>>(iterator: I) -> Self {
2463 /// let mut c = MyCollection::new();
2465 /// for i in iterator {
2473 /// // Now we can make a new iterator...
2474 /// let iter = (0..5).into_iter();
2476 /// // ... and make a MyCollection out of it
2477 /// let c = MyCollection::from_iter(iter);
2479 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
2481 /// // collect works too!
2483 /// let iter = (0..5).into_iter();
2484 /// let c: MyCollection = iter.collect();
2486 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
2488 #[stable(feature = "rust1", since = "1.0.0")]
2489 #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
2490 built from an iterator over elements of type `{A}`"]
2491 pub trait FromIterator
<A
>: Sized
{
2492 /// Creates a value from an iterator.
2494 /// See the [module-level documentation] for more.
2496 /// [module-level documentation]: trait.FromIterator.html
2503 /// use std::iter::FromIterator;
2505 /// let five_fives = std::iter::repeat(5).take(5);
2507 /// let v = Vec::from_iter(five_fives);
2509 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2511 #[stable(feature = "rust1", since = "1.0.0")]
2512 fn from_iter
<T
: IntoIterator
<Item
=A
>>(iterator
: T
) -> Self;
2515 /// Conversion into an `Iterator`.
2517 /// By implementing `IntoIterator` for a type, you define how it will be
2518 /// converted to an iterator. This is common for types which describe a
2519 /// collection of some kind.
2521 /// One benefit of implementing `IntoIterator` is that your type will [work
2522 /// with Rust's `for` loop syntax](index.html#for-loops-and-intoiterator).
2524 /// See also: [`FromIterator`].
2526 /// [`FromIterator`]: trait.FromIterator.html
2533 /// let v = vec![1, 2, 3];
2535 /// let mut iter = v.into_iter();
2537 /// let n = iter.next();
2538 /// assert_eq!(Some(1), n);
2540 /// let n = iter.next();
2541 /// assert_eq!(Some(2), n);
2543 /// let n = iter.next();
2544 /// assert_eq!(Some(3), n);
2546 /// let n = iter.next();
2547 /// assert_eq!(None, n);
2550 /// Implementing `IntoIterator` for your type:
2553 /// // A sample collection, that's just a wrapper over Vec<T>
2554 /// #[derive(Debug)]
2555 /// struct MyCollection(Vec<i32>);
2557 /// // Let's give it some methods so we can create one and add things
2559 /// impl MyCollection {
2560 /// fn new() -> MyCollection {
2561 /// MyCollection(Vec::new())
2564 /// fn add(&mut self, elem: i32) {
2565 /// self.0.push(elem);
2569 /// // and we'll implement IntoIterator
2570 /// impl IntoIterator for MyCollection {
2571 /// type Item = i32;
2572 /// type IntoIter = ::std::vec::IntoIter<i32>;
2574 /// fn into_iter(self) -> Self::IntoIter {
2575 /// self.0.into_iter()
2579 /// // Now we can make a new collection...
2580 /// let mut c = MyCollection::new();
2582 /// // ... add some stuff to it ...
2587 /// // ... and then turn it into an Iterator:
2588 /// for (i, n) in c.into_iter().enumerate() {
2589 /// assert_eq!(i as i32, n);
2592 #[stable(feature = "rust1", since = "1.0.0")]
2593 pub trait IntoIterator
{
2594 /// The type of the elements being iterated over.
2595 #[stable(feature = "rust1", since = "1.0.0")]
2598 /// Which kind of iterator are we turning this into?
2599 #[stable(feature = "rust1", since = "1.0.0")]
2600 type IntoIter
: Iterator
<Item
=Self::Item
>;
2602 /// Creates an iterator from a value.
2604 /// See the [module-level documentation] for more.
2606 /// [module-level documentation]: trait.IntoIterator.html
2613 /// let v = vec![1, 2, 3];
2615 /// let mut iter = v.into_iter();
2617 /// let n = iter.next();
2618 /// assert_eq!(Some(1), n);
2620 /// let n = iter.next();
2621 /// assert_eq!(Some(2), n);
2623 /// let n = iter.next();
2624 /// assert_eq!(Some(3), n);
2626 /// let n = iter.next();
2627 /// assert_eq!(None, n);
2629 #[stable(feature = "rust1", since = "1.0.0")]
2630 fn into_iter(self) -> Self::IntoIter
;
2633 #[stable(feature = "rust1", since = "1.0.0")]
2634 impl<I
: Iterator
> IntoIterator
for I
{
2635 type Item
= I
::Item
;
2638 fn into_iter(self) -> I
{
2643 /// Extend a collection with the contents of an iterator.
2645 /// Iterators produce a series of values, and collections can also be thought
2646 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
2647 /// to extend a collection by including the contents of that iterator.
2654 /// // You can extend a String with some chars:
2655 /// let mut message = String::from("The first three letters are: ");
2657 /// message.extend(&['a', 'b', 'c']);
2659 /// assert_eq!("abc", &message[29..32]);
2662 /// Implementing `Extend`:
2665 /// // A sample collection, that's just a wrapper over Vec<T>
2666 /// #[derive(Debug)]
2667 /// struct MyCollection(Vec<i32>);
2669 /// // Let's give it some methods so we can create one and add things
2671 /// impl MyCollection {
2672 /// fn new() -> MyCollection {
2673 /// MyCollection(Vec::new())
2676 /// fn add(&mut self, elem: i32) {
2677 /// self.0.push(elem);
2681 /// // since MyCollection has a list of i32s, we implement Extend for i32
2682 /// impl Extend<i32> for MyCollection {
2684 /// // This is a bit simpler with the concrete type signature: we can call
2685 /// // extend on anything which can be turned into an Iterator which gives
2686 /// // us i32s. Because we need i32s to put into MyCollection.
2687 /// fn extend<T: IntoIterator<Item=i32>>(&mut self, iterable: T) {
2689 /// // The implementation is very straightforward: loop through the
2690 /// // iterator, and add() each element to ourselves.
2691 /// for elem in iterable {
2697 /// let mut c = MyCollection::new();
2703 /// // let's extend our collection with three more numbers
2704 /// c.extend(vec![1, 2, 3]);
2706 /// // we've added these elements onto the end
2707 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
2709 #[stable(feature = "rust1", since = "1.0.0")]
2710 pub trait Extend
<A
> {
2711 /// Extends a collection with the contents of an iterator.
2713 /// As this is the only method for this trait, the [trait-level] docs
2714 /// contain more details.
2716 /// [trait-level]: trait.Extend.html
2723 /// // You can extend a String with some chars:
2724 /// let mut message = String::from("abc");
2726 /// message.extend(['d', 'e', 'f'].iter());
2728 /// assert_eq!("abcdef", &message);
2730 #[stable(feature = "rust1", since = "1.0.0")]
2731 fn extend
<T
: IntoIterator
<Item
=A
>>(&mut self, iterable
: T
);
2734 /// An iterator able to yield elements from both ends.
2736 /// Something that implements `DoubleEndedIterator` has one extra capability
2737 /// over something that implements [`Iterator`]: the ability to also take
2738 /// `Item`s from the back, as well as the front.
2740 /// It is important to note that both back and forth work on the same range,
2741 /// and do not cross: iteration is over when they meet in the middle.
2743 /// [`Iterator`]: trait.Iterator.html
2749 /// let numbers = vec![1, 2, 3];
2751 /// let mut iter = numbers.iter();
2753 /// let n = iter.next();
2754 /// assert_eq!(Some(&1), n);
2756 /// let n = iter.next_back();
2757 /// assert_eq!(Some(&3), n);
2759 /// let n = iter.next_back();
2760 /// assert_eq!(Some(&2), n);
2762 /// let n = iter.next();
2763 /// assert_eq!(None, n);
2765 /// let n = iter.next_back();
2766 /// assert_eq!(None, n);
2768 #[stable(feature = "rust1", since = "1.0.0")]
2769 pub trait DoubleEndedIterator
: Iterator
{
2770 /// An iterator able to yield elements from both ends.
2772 /// As this is the only method for this trait, the [trait-level] docs
2773 /// contain more details.
2775 /// [trait-level]: trait.DoubleEndedIterator.html
2782 /// let numbers = vec![1, 2, 3];
2784 /// let mut iter = numbers.iter();
2786 /// let n = iter.next();
2787 /// assert_eq!(Some(&1), n);
2789 /// let n = iter.next_back();
2790 /// assert_eq!(Some(&3), n);
2792 /// let n = iter.next_back();
2793 /// assert_eq!(Some(&2), n);
2795 /// let n = iter.next();
2796 /// assert_eq!(None, n);
2798 /// let n = iter.next_back();
2799 /// assert_eq!(None, n);
2801 #[stable(feature = "rust1", since = "1.0.0")]
2802 fn next_back(&mut self) -> Option
<Self::Item
>;
2805 #[stable(feature = "rust1", since = "1.0.0")]
2806 impl<'a
, I
: DoubleEndedIterator
+ ?Sized
> DoubleEndedIterator
for &'a
mut I
{
2807 fn next_back(&mut self) -> Option
<I
::Item
> { (**self).next_back() }
2810 /// An iterator that knows its exact length.
2812 /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
2813 /// If an iterator knows how many times it can iterate, providing access to
2814 /// that information can be useful. For example, if you want to iterate
2815 /// backwards, a good start is to know where the end is.
2817 /// When implementing an `ExactSizeIterator`, You must also implement
2818 /// [`Iterator`]. When doing so, the implementation of [`size_hint()`] *must*
2819 /// return the exact size of the iterator.
2821 /// [`Iterator`]: trait.Iterator.html
2822 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
2824 /// The [`len()`] method has a default implementation, so you usually shouldn't
2825 /// implement it. However, you may be able to provide a more performant
2826 /// implementation than the default, so overriding it in this case makes sense.
2828 /// [`len()`]: #method.len
2835 /// // a finite range knows exactly how many times it will iterate
2836 /// let five = 0..5;
2838 /// assert_eq!(5, five.len());
2841 /// In the [module level docs][moddocs], we implemented an [`Iterator`],
2842 /// `Counter`. Let's implement `ExactSizeIterator` for it as well:
2844 /// [moddocs]: index.html
2847 /// # struct Counter {
2850 /// # impl Counter {
2851 /// # fn new() -> Counter {
2852 /// # Counter { count: 0 }
2855 /// # impl Iterator for Counter {
2856 /// # type Item = usize;
2857 /// # fn next(&mut self) -> Option<usize> {
2858 /// # self.count += 1;
2859 /// # if self.count < 6 {
2860 /// # Some(self.count)
2866 /// impl ExactSizeIterator for Counter {
2867 /// // We already have the number of iterations, so we can use it directly.
2868 /// fn len(&self) -> usize {
2873 /// // And now we can use it!
2875 /// let counter = Counter::new();
2877 /// assert_eq!(0, counter.len());
2879 #[stable(feature = "rust1", since = "1.0.0")]
2880 pub trait ExactSizeIterator
: Iterator
{
2882 #[stable(feature = "rust1", since = "1.0.0")]
2883 /// Returns the exact number of times the iterator will iterate.
2885 /// This method has a default implementation, so you usually should not
2886 /// implement it directly. However, if you can provide a more efficient
2887 /// implementation, you can do so. See the [trait-level] docs for an
2890 /// This function has the same safety guarantees as the [`size_hint()`]
2893 /// [trait-level]: trait.ExactSizeIterator.html
2894 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
2901 /// // a finite range knows exactly how many times it will iterate
2902 /// let five = 0..5;
2904 /// assert_eq!(5, five.len());
2906 fn len(&self) -> usize {
2907 let (lower
, upper
) = self.size_hint();
2908 // Note: This assertion is overly defensive, but it checks the invariant
2909 // guaranteed by the trait. If this trait were rust-internal,
2910 // we could use debug_assert!; assert_eq! will check all Rust user
2911 // implementations too.
2912 assert_eq
!(upper
, Some(lower
));
2917 #[stable(feature = "rust1", since = "1.0.0")]
2918 impl<'a
, I
: ExactSizeIterator
+ ?Sized
> ExactSizeIterator
for &'a
mut I {}
2920 // All adaptors that preserve the size of the wrapped iterator are fine
2921 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
2922 #[stable(feature = "rust1", since = "1.0.0")]
2923 impl<I
> ExactSizeIterator
for Enumerate
<I
> where I
: ExactSizeIterator {}
2924 #[stable(feature = "rust1", since = "1.0.0")]
2925 impl<I
: ExactSizeIterator
, F
> ExactSizeIterator
for Inspect
<I
, F
> where
2928 #[stable(feature = "rust1", since = "1.0.0")]
2929 impl<I
> ExactSizeIterator
for Rev
<I
>
2930 where I
: ExactSizeIterator
+ DoubleEndedIterator {}
2931 #[stable(feature = "rust1", since = "1.0.0")]
2932 impl<B
, I
: ExactSizeIterator
, F
> ExactSizeIterator
for Map
<I
, F
> where
2933 F
: FnMut(I
::Item
) -> B
,
2935 #[stable(feature = "rust1", since = "1.0.0")]
2936 impl<A
, B
> ExactSizeIterator
for Zip
<A
, B
>
2937 where A
: ExactSizeIterator
, B
: ExactSizeIterator {}
2939 /// An double-ended iterator with the direction inverted.
2941 /// This `struct` is created by the [`rev()`] method on [`Iterator`]. See its
2942 /// documentation for more.
2944 /// [`rev()`]: trait.Iterator.html#method.rev
2945 /// [`Iterator`]: trait.Iterator.html
2947 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2948 #[stable(feature = "rust1", since = "1.0.0")]
2953 #[stable(feature = "rust1", since = "1.0.0")]
2954 impl<I
> Iterator
for Rev
<I
> where I
: DoubleEndedIterator
{
2955 type Item
= <I
as Iterator
>::Item
;
2958 fn next(&mut self) -> Option
<<I
as Iterator
>::Item
> { self.iter.next_back() }
2960 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
2963 #[stable(feature = "rust1", since = "1.0.0")]
2964 impl<I
> DoubleEndedIterator
for Rev
<I
> where I
: DoubleEndedIterator
{
2966 fn next_back(&mut self) -> Option
<<I
as Iterator
>::Item
> { self.iter.next() }
2969 /// An iterator that clones the elements of an underlying iterator.
2971 /// This `struct` is created by the [`cloned()`] method on [`Iterator`]. See its
2972 /// documentation for more.
2974 /// [`cloned()`]: trait.Iterator.html#method.cloned
2975 /// [`Iterator`]: trait.Iterator.html
2976 #[stable(feature = "iter_cloned", since = "1.1.0")]
2977 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2979 pub struct Cloned
<I
> {
2983 #[stable(feature = "rust1", since = "1.0.0")]
2984 impl<'a
, I
, T
: 'a
> Iterator
for Cloned
<I
>
2985 where I
: Iterator
<Item
=&'a T
>, T
: Clone
2989 fn next(&mut self) -> Option
<T
> {
2990 self.it
.next().cloned()
2993 fn size_hint(&self) -> (usize, Option
<usize>) {
2998 #[stable(feature = "rust1", since = "1.0.0")]
2999 impl<'a
, I
, T
: 'a
> DoubleEndedIterator
for Cloned
<I
>
3000 where I
: DoubleEndedIterator
<Item
=&'a T
>, T
: Clone
3002 fn next_back(&mut self) -> Option
<T
> {
3003 self.it
.next_back().cloned()
3007 #[stable(feature = "rust1", since = "1.0.0")]
3008 impl<'a
, I
, T
: 'a
> ExactSizeIterator
for Cloned
<I
>
3009 where I
: ExactSizeIterator
<Item
=&'a T
>, T
: Clone
3012 /// An iterator that repeats endlessly.
3014 /// This `struct` is created by the [`cycle()`] method on [`Iterator`]. See its
3015 /// documentation for more.
3017 /// [`cycle()`]: trait.Iterator.html#method.cycle
3018 /// [`Iterator`]: trait.Iterator.html
3020 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3021 #[stable(feature = "rust1", since = "1.0.0")]
3022 pub struct Cycle
<I
> {
3027 #[stable(feature = "rust1", since = "1.0.0")]
3028 impl<I
> Iterator
for Cycle
<I
> where I
: Clone
+ Iterator
{
3029 type Item
= <I
as Iterator
>::Item
;
3032 fn next(&mut self) -> Option
<<I
as Iterator
>::Item
> {
3033 match self.iter
.next() {
3034 None
=> { self.iter = self.orig.clone(); self.iter.next() }
3040 fn size_hint(&self) -> (usize, Option
<usize>) {
3041 // the cycle iterator is either empty or infinite
3042 match self.orig
.size_hint() {
3043 sz @
(0, Some(0)) => sz
,
3044 (0, _
) => (0, None
),
3045 _
=> (usize::MAX
, None
)
3050 /// An iterator that strings two iterators together.
3052 /// This `struct` is created by the [`chain()`] method on [`Iterator`]. See its
3053 /// documentation for more.
3055 /// [`chain()`]: trait.Iterator.html#method.chain
3056 /// [`Iterator`]: trait.Iterator.html
3058 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3059 #[stable(feature = "rust1", since = "1.0.0")]
3060 pub struct Chain
<A
, B
> {
3066 // The iterator protocol specifies that iteration ends with the return value
3067 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
3068 // further calls return. The chain adaptor must account for this since it uses
3069 // two subiterators.
3071 // It uses three states:
3073 // - Both: `a` and `b` are remaining
3074 // - Front: `a` remaining
3075 // - Back: `b` remaining
3077 // The fourth state (neither iterator is remaining) only occurs after Chain has
3078 // returned None once, so we don't need to store this state.
3081 // both front and back iterator are remaining
3083 // only front is remaining
3085 // only back is remaining
3089 #[stable(feature = "rust1", since = "1.0.0")]
3090 impl<A
, B
> Iterator
for Chain
<A
, B
> where
3092 B
: Iterator
<Item
= A
::Item
>
3094 type Item
= A
::Item
;
3097 fn next(&mut self) -> Option
<A
::Item
> {
3099 ChainState
::Both
=> match self.a
.next() {
3100 elt @
Some(..) => elt
,
3102 self.state
= ChainState
::Back
;
3106 ChainState
::Front
=> self.a
.next(),
3107 ChainState
::Back
=> self.b
.next(),
3112 fn count(self) -> usize {
3114 ChainState
::Both
=> self.a
.count() + self.b
.count(),
3115 ChainState
::Front
=> self.a
.count(),
3116 ChainState
::Back
=> self.b
.count(),
3121 fn nth(&mut self, mut n
: usize) -> Option
<A
::Item
> {
3123 ChainState
::Both
| ChainState
::Front
=> {
3124 for x
in self.a
.by_ref() {
3130 if let ChainState
::Both
= self.state
{
3131 self.state
= ChainState
::Back
;
3134 ChainState
::Back
=> {}
3136 if let ChainState
::Back
= self.state
{
3144 fn last(self) -> Option
<A
::Item
> {
3146 ChainState
::Both
=> {
3147 // Must exhaust a before b.
3148 let a_last
= self.a
.last();
3149 let b_last
= self.b
.last();
3152 ChainState
::Front
=> self.a
.last(),
3153 ChainState
::Back
=> self.b
.last()
3158 fn size_hint(&self) -> (usize, Option
<usize>) {
3159 let (a_lower
, a_upper
) = self.a
.size_hint();
3160 let (b_lower
, b_upper
) = self.b
.size_hint();
3162 let lower
= a_lower
.saturating_add(b_lower
);
3164 let upper
= match (a_upper
, b_upper
) {
3165 (Some(x
), Some(y
)) => x
.checked_add(y
),
3173 #[stable(feature = "rust1", since = "1.0.0")]
3174 impl<A
, B
> DoubleEndedIterator
for Chain
<A
, B
> where
3175 A
: DoubleEndedIterator
,
3176 B
: DoubleEndedIterator
<Item
=A
::Item
>,
3179 fn next_back(&mut self) -> Option
<A
::Item
> {
3181 ChainState
::Both
=> match self.b
.next_back() {
3182 elt @
Some(..) => elt
,
3184 self.state
= ChainState
::Front
;
3188 ChainState
::Front
=> self.a
.next_back(),
3189 ChainState
::Back
=> self.b
.next_back(),
3194 /// An iterator that iterates two other iterators simultaneously.
3196 /// This `struct` is created by the [`zip()`] method on [`Iterator`]. See its
3197 /// documentation for more.
3199 /// [`zip()`]: trait.Iterator.html#method.zip
3200 /// [`Iterator`]: trait.Iterator.html
3202 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3203 #[stable(feature = "rust1", since = "1.0.0")]
3204 pub struct Zip
<A
, B
> {
3209 #[stable(feature = "rust1", since = "1.0.0")]
3210 impl<A
, B
> Iterator
for Zip
<A
, B
> where A
: Iterator
, B
: Iterator
3212 type Item
= (A
::Item
, B
::Item
);
3215 fn next(&mut self) -> Option
<(A
::Item
, B
::Item
)> {
3216 self.a
.next().and_then(|x
| {
3217 self.b
.next().and_then(|y
| {
3224 fn size_hint(&self) -> (usize, Option
<usize>) {
3225 let (a_lower
, a_upper
) = self.a
.size_hint();
3226 let (b_lower
, b_upper
) = self.b
.size_hint();
3228 let lower
= cmp
::min(a_lower
, b_lower
);
3230 let upper
= match (a_upper
, b_upper
) {
3231 (Some(x
), Some(y
)) => Some(cmp
::min(x
,y
)),
3232 (Some(x
), None
) => Some(x
),
3233 (None
, Some(y
)) => Some(y
),
3234 (None
, None
) => None
3241 #[stable(feature = "rust1", since = "1.0.0")]
3242 impl<A
, B
> DoubleEndedIterator
for Zip
<A
, B
> where
3243 A
: DoubleEndedIterator
+ ExactSizeIterator
,
3244 B
: DoubleEndedIterator
+ ExactSizeIterator
,
3247 fn next_back(&mut self) -> Option
<(A
::Item
, B
::Item
)> {
3248 let a_sz
= self.a
.len();
3249 let b_sz
= self.b
.len();
3251 // Adjust a, b to equal length
3253 for _
in 0..a_sz
- b_sz { self.a.next_back(); }
3255 for _
in 0..b_sz
- a_sz { self.b.next_back(); }
3258 match (self.a
.next_back(), self.b
.next_back()) {
3259 (Some(x
), Some(y
)) => Some((x
, y
)),
3260 (None
, None
) => None
,
3261 _
=> unreachable
!(),
3266 /// An iterator that maps the values of `iter` with `f`.
3268 /// This `struct` is created by the [`map()`] method on [`Iterator`]. See its
3269 /// documentation for more.
3271 /// [`map()`]: trait.Iterator.html#method.map
3272 /// [`Iterator`]: trait.Iterator.html
3273 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3274 #[stable(feature = "rust1", since = "1.0.0")]
3276 pub struct Map
<I
, F
> {
3281 #[stable(feature = "rust1", since = "1.0.0")]
3282 impl<B
, I
: Iterator
, F
> Iterator
for Map
<I
, F
> where F
: FnMut(I
::Item
) -> B
{
3286 fn next(&mut self) -> Option
<B
> {
3287 self.iter
.next().map(&mut self.f
)
3291 fn size_hint(&self) -> (usize, Option
<usize>) {
3292 self.iter
.size_hint()
3296 #[stable(feature = "rust1", since = "1.0.0")]
3297 impl<B
, I
: DoubleEndedIterator
, F
> DoubleEndedIterator
for Map
<I
, F
> where
3298 F
: FnMut(I
::Item
) -> B
,
3301 fn next_back(&mut self) -> Option
<B
> {
3302 self.iter
.next_back().map(&mut self.f
)
3306 /// An iterator that filters the elements of `iter` with `predicate`.
3308 /// This `struct` is created by the [`filter()`] method on [`Iterator`]. See its
3309 /// documentation for more.
3311 /// [`filter()`]: trait.Iterator.html#method.filter
3312 /// [`Iterator`]: trait.Iterator.html
3313 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3314 #[stable(feature = "rust1", since = "1.0.0")]
3316 pub struct Filter
<I
, P
> {
3321 #[stable(feature = "rust1", since = "1.0.0")]
3322 impl<I
: Iterator
, P
> Iterator
for Filter
<I
, P
> where P
: FnMut(&I
::Item
) -> bool
{
3323 type Item
= I
::Item
;
3326 fn next(&mut self) -> Option
<I
::Item
> {
3327 for x
in self.iter
.by_ref() {
3328 if (self.predicate
)(&x
) {
3336 fn size_hint(&self) -> (usize, Option
<usize>) {
3337 let (_
, upper
) = self.iter
.size_hint();
3338 (0, upper
) // can't know a lower bound, due to the predicate
3342 #[stable(feature = "rust1", since = "1.0.0")]
3343 impl<I
: DoubleEndedIterator
, P
> DoubleEndedIterator
for Filter
<I
, P
>
3344 where P
: FnMut(&I
::Item
) -> bool
,
3347 fn next_back(&mut self) -> Option
<I
::Item
> {
3348 for x
in self.iter
.by_ref().rev() {
3349 if (self.predicate
)(&x
) {
3357 /// An iterator that uses `f` to both filter and map elements from `iter`.
3359 /// This `struct` is created by the [`filter_map()`] method on [`Iterator`]. See its
3360 /// documentation for more.
3362 /// [`filter_map()`]: trait.Iterator.html#method.filter_map
3363 /// [`Iterator`]: trait.Iterator.html
3364 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3365 #[stable(feature = "rust1", since = "1.0.0")]
3367 pub struct FilterMap
<I
, F
> {
3372 #[stable(feature = "rust1", since = "1.0.0")]
3373 impl<B
, I
: Iterator
, F
> Iterator
for FilterMap
<I
, F
>
3374 where F
: FnMut(I
::Item
) -> Option
<B
>,
3379 fn next(&mut self) -> Option
<B
> {
3380 for x
in self.iter
.by_ref() {
3381 if let Some(y
) = (self.f
)(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<B
, I
: DoubleEndedIterator
, F
> DoubleEndedIterator
for FilterMap
<I
, F
>
3397 where F
: FnMut(I
::Item
) -> Option
<B
>,
3400 fn next_back(&mut self) -> Option
<B
> {
3401 for x
in self.iter
.by_ref().rev() {
3402 if let Some(y
) = (self.f
)(x
) {
3410 /// An iterator that yields the current count and the element during iteration.
3412 /// This `struct` is created by the [`enumerate()`] method on [`Iterator`]. See its
3413 /// documentation for more.
3415 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
3416 /// [`Iterator`]: trait.Iterator.html
3418 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3419 #[stable(feature = "rust1", since = "1.0.0")]
3420 pub struct Enumerate
<I
> {
3425 #[stable(feature = "rust1", since = "1.0.0")]
3426 impl<I
> Iterator
for Enumerate
<I
> where I
: Iterator
{
3427 type Item
= (usize, <I
as Iterator
>::Item
);
3429 /// # Overflow Behavior
3431 /// The method does no guarding against overflows, so enumerating more than
3432 /// `usize::MAX` elements either produces the wrong result or panics. If
3433 /// debug assertions are enabled, a panic is guaranteed.
3437 /// Might panic if the index of the element overflows a `usize`.
3439 fn next(&mut self) -> Option
<(usize, <I
as Iterator
>::Item
)> {
3440 self.iter
.next().map(|a
| {
3441 let ret
= (self.count
, a
);
3442 // Possible undefined overflow.
3449 fn size_hint(&self) -> (usize, Option
<usize>) {
3450 self.iter
.size_hint()
3454 fn nth(&mut self, n
: usize) -> Option
<(usize, I
::Item
)> {
3455 self.iter
.nth(n
).map(|a
| {
3456 let i
= self.count
+ n
;
3463 fn count(self) -> usize {
3468 #[stable(feature = "rust1", since = "1.0.0")]
3469 impl<I
> DoubleEndedIterator
for Enumerate
<I
> where
3470 I
: ExactSizeIterator
+ DoubleEndedIterator
3473 fn next_back(&mut self) -> Option
<(usize, <I
as Iterator
>::Item
)> {
3474 self.iter
.next_back().map(|a
| {
3475 let len
= self.iter
.len();
3476 // Can safely add, `ExactSizeIterator` promises that the number of
3477 // elements fits into a `usize`.
3478 (self.count
+ len
, a
)
3483 /// An iterator with a `peek()` that returns an optional reference to the next
3486 /// This `struct` is created by the [`peekable()`] method on [`Iterator`]. See its
3487 /// documentation for more.
3489 /// [`peekable()`]: trait.Iterator.html#method.peekable
3490 /// [`Iterator`]: trait.Iterator.html
3492 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3493 #[stable(feature = "rust1", since = "1.0.0")]
3494 pub struct Peekable
<I
: Iterator
> {
3496 peeked
: Option
<I
::Item
>,
3499 #[stable(feature = "rust1", since = "1.0.0")]
3500 impl<I
: Iterator
> Iterator
for Peekable
<I
> {
3501 type Item
= I
::Item
;
3504 fn next(&mut self) -> Option
<I
::Item
> {
3506 Some(_
) => self.peeked
.take(),
3507 None
=> self.iter
.next(),
3512 fn count(self) -> usize {
3513 (if self.peeked
.is_some() { 1 }
else { 0 }
) + self.iter
.count()
3517 fn nth(&mut self, n
: usize) -> Option
<I
::Item
> {
3519 Some(_
) if n
== 0 => self.peeked
.take(),
3524 None
=> self.iter
.nth(n
)
3529 fn last(self) -> Option
<I
::Item
> {
3530 self.iter
.last().or(self.peeked
)
3534 fn size_hint(&self) -> (usize, Option
<usize>) {
3535 let (lo
, hi
) = self.iter
.size_hint();
3536 if self.peeked
.is_some() {
3537 let lo
= lo
.saturating_add(1);
3538 let hi
= hi
.and_then(|x
| x
.checked_add(1));
3546 #[stable(feature = "rust1", since = "1.0.0")]
3547 impl<I
: ExactSizeIterator
> ExactSizeIterator
for Peekable
<I
> {}
3549 impl<I
: Iterator
> Peekable
<I
> {
3550 /// Returns a reference to the next() value without advancing the iterator.
3552 /// The `peek()` method will return the value that a call to [`next()`] would
3553 /// return, but does not advance the iterator. Like [`next()`], if there is
3554 /// a value, it's wrapped in a `Some(T)`, but if the iterator is over, it
3555 /// will return `None`.
3557 /// [`next()`]: trait.Iterator.html#tymethod.next
3559 /// Because `peek()` returns reference, and many iterators iterate over
3560 /// references, this leads to a possibly confusing situation where the
3561 /// return value is a double reference. You can see this effect in the
3562 /// examples below, with `&&i32`.
3569 /// let xs = [1, 2, 3];
3571 /// let mut iter = xs.iter().peekable();
3573 /// // peek() lets us see into the future
3574 /// assert_eq!(iter.peek(), Some(&&1));
3575 /// assert_eq!(iter.next(), Some(&1));
3577 /// assert_eq!(iter.next(), Some(&2));
3579 /// // we can peek() multiple times, the iterator won't advance
3580 /// assert_eq!(iter.peek(), Some(&&3));
3581 /// assert_eq!(iter.peek(), Some(&&3));
3583 /// assert_eq!(iter.next(), Some(&3));
3585 /// // after the iterator is finished, so is peek()
3586 /// assert_eq!(iter.peek(), None);
3587 /// assert_eq!(iter.next(), None);
3590 #[stable(feature = "rust1", since = "1.0.0")]
3591 pub fn peek(&mut self) -> Option
<&I
::Item
> {
3592 if self.peeked
.is_none() {
3593 self.peeked
= self.iter
.next();
3596 Some(ref value
) => Some(value
),
3601 /// Checks if the iterator has finished iterating.
3603 /// Returns `true` if there are no more elements in the iterator, and
3604 /// `false` if there are.
3611 /// #![feature(peekable_is_empty)]
3613 /// let xs = [1, 2, 3];
3615 /// let mut iter = xs.iter().peekable();
3617 /// // there are still elements to iterate over
3618 /// assert_eq!(iter.is_empty(), false);
3620 /// // let's consume the iterator
3625 /// assert_eq!(iter.is_empty(), true);
3627 #[unstable(feature = "peekable_is_empty", issue = "27701")]
3629 pub fn is_empty(&mut self) -> bool
{
3630 self.peek().is_none()
3634 /// An iterator that rejects elements while `predicate` is true.
3636 /// This `struct` is created by the [`skip_while()`] method on [`Iterator`]. See its
3637 /// documentation for more.
3639 /// [`skip_while()`]: trait.Iterator.html#method.skip_while
3640 /// [`Iterator`]: trait.Iterator.html
3641 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3642 #[stable(feature = "rust1", since = "1.0.0")]
3644 pub struct SkipWhile
<I
, P
> {
3650 #[stable(feature = "rust1", since = "1.0.0")]
3651 impl<I
: Iterator
, P
> Iterator
for SkipWhile
<I
, P
>
3652 where P
: FnMut(&I
::Item
) -> bool
3654 type Item
= I
::Item
;
3657 fn next(&mut self) -> Option
<I
::Item
> {
3658 for x
in self.iter
.by_ref() {
3659 if self.flag
|| !(self.predicate
)(&x
) {
3668 fn size_hint(&self) -> (usize, Option
<usize>) {
3669 let (_
, upper
) = self.iter
.size_hint();
3670 (0, upper
) // can't know a lower bound, due to the predicate
3674 /// An iterator that only accepts elements while `predicate` is true.
3676 /// This `struct` is created by the [`take_while()`] method on [`Iterator`]. See its
3677 /// documentation for more.
3679 /// [`take_while()`]: trait.Iterator.html#method.take_while
3680 /// [`Iterator`]: trait.Iterator.html
3681 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3682 #[stable(feature = "rust1", since = "1.0.0")]
3684 pub struct TakeWhile
<I
, P
> {
3690 #[stable(feature = "rust1", since = "1.0.0")]
3691 impl<I
: Iterator
, P
> Iterator
for TakeWhile
<I
, P
>
3692 where P
: FnMut(&I
::Item
) -> bool
3694 type Item
= I
::Item
;
3697 fn next(&mut self) -> Option
<I
::Item
> {
3701 self.iter
.next().and_then(|x
| {
3702 if (self.predicate
)(&x
) {
3713 fn size_hint(&self) -> (usize, Option
<usize>) {
3714 let (_
, upper
) = self.iter
.size_hint();
3715 (0, upper
) // can't know a lower bound, due to the predicate
3719 /// An iterator that skips over `n` elements of `iter`.
3721 /// This `struct` is created by the [`skip()`] method on [`Iterator`]. See its
3722 /// documentation for more.
3724 /// [`skip()`]: trait.Iterator.html#method.skip
3725 /// [`Iterator`]: trait.Iterator.html
3727 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3728 #[stable(feature = "rust1", since = "1.0.0")]
3729 pub struct Skip
<I
> {
3734 #[stable(feature = "rust1", since = "1.0.0")]
3735 impl<I
> Iterator
for Skip
<I
> where I
: Iterator
{
3736 type Item
= <I
as Iterator
>::Item
;
3739 fn next(&mut self) -> Option
<I
::Item
> {
3745 self.iter
.nth(old_n
)
3750 fn nth(&mut self, n
: usize) -> Option
<I
::Item
> {
3751 // Can't just add n + self.n due to overflow.
3755 let to_skip
= self.n
;
3758 if self.iter
.nth(to_skip
-1).is_none() {
3766 fn count(self) -> usize {
3767 self.iter
.count().saturating_sub(self.n
)
3771 fn last(mut self) -> Option
<I
::Item
> {
3775 let next
= self.next();
3777 // recurse. n should be 0.
3778 self.last().or(next
)
3786 fn size_hint(&self) -> (usize, Option
<usize>) {
3787 let (lower
, upper
) = self.iter
.size_hint();
3789 let lower
= lower
.saturating_sub(self.n
);
3790 let upper
= upper
.map(|x
| x
.saturating_sub(self.n
));
3796 #[stable(feature = "rust1", since = "1.0.0")]
3797 impl<I
> ExactSizeIterator
for Skip
<I
> where I
: ExactSizeIterator {}
3799 /// An iterator that only iterates over the first `n` iterations of `iter`.
3801 /// This `struct` is created by the [`take()`] method on [`Iterator`]. See its
3802 /// documentation for more.
3804 /// [`take()`]: trait.Iterator.html#method.take
3805 /// [`Iterator`]: trait.Iterator.html
3807 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3808 #[stable(feature = "rust1", since = "1.0.0")]
3809 pub struct Take
<I
> {
3814 #[stable(feature = "rust1", since = "1.0.0")]
3815 impl<I
> Iterator
for Take
<I
> where I
: Iterator
{
3816 type Item
= <I
as Iterator
>::Item
;
3819 fn next(&mut self) -> Option
<<I
as Iterator
>::Item
> {
3829 fn nth(&mut self, n
: usize) -> Option
<I
::Item
> {
3835 self.iter
.nth(self.n
- 1);
3843 fn size_hint(&self) -> (usize, Option
<usize>) {
3844 let (lower
, upper
) = self.iter
.size_hint();
3846 let lower
= cmp
::min(lower
, self.n
);
3848 let upper
= match upper
{
3849 Some(x
) if x
< self.n
=> Some(x
),
3857 #[stable(feature = "rust1", since = "1.0.0")]
3858 impl<I
> ExactSizeIterator
for Take
<I
> where I
: ExactSizeIterator {}
3861 /// An iterator to maintain state while iterating another iterator.
3863 /// This `struct` is created by the [`scan()`] method on [`Iterator`]. See its
3864 /// documentation for more.
3866 /// [`scan()`]: trait.Iterator.html#method.scan
3867 /// [`Iterator`]: trait.Iterator.html
3868 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3869 #[stable(feature = "rust1", since = "1.0.0")]
3871 pub struct Scan
<I
, St
, F
> {
3877 #[stable(feature = "rust1", since = "1.0.0")]
3878 impl<B
, I
, St
, F
> Iterator
for Scan
<I
, St
, F
> where
3880 F
: FnMut(&mut St
, I
::Item
) -> Option
<B
>,
3885 fn next(&mut self) -> Option
<B
> {
3886 self.iter
.next().and_then(|a
| (self.f
)(&mut self.state
, a
))
3890 fn size_hint(&self) -> (usize, Option
<usize>) {
3891 let (_
, upper
) = self.iter
.size_hint();
3892 (0, upper
) // can't know a lower bound, due to the scan function
3896 /// An iterator that maps each element to an iterator, and yields the elements
3897 /// of the produced iterators.
3899 /// This `struct` is created by the [`flat_map()`] method on [`Iterator`]. See its
3900 /// documentation for more.
3902 /// [`flat_map()`]: trait.Iterator.html#method.flat_map
3903 /// [`Iterator`]: trait.Iterator.html
3904 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3905 #[stable(feature = "rust1", since = "1.0.0")]
3907 pub struct FlatMap
<I
, U
: IntoIterator
, F
> {
3910 frontiter
: Option
<U
::IntoIter
>,
3911 backiter
: Option
<U
::IntoIter
>,
3914 #[stable(feature = "rust1", since = "1.0.0")]
3915 impl<I
: Iterator
, U
: IntoIterator
, F
> Iterator
for FlatMap
<I
, U
, F
>
3916 where F
: FnMut(I
::Item
) -> U
,
3918 type Item
= U
::Item
;
3921 fn next(&mut self) -> Option
<U
::Item
> {
3923 if let Some(ref mut inner
) = self.frontiter
{
3924 if let Some(x
) = inner
.by_ref().next() {
3928 match self.iter
.next().map(&mut self.f
) {
3929 None
=> return self.backiter
.as_mut().and_then(|it
| it
.next()),
3930 next
=> self.frontiter
= next
.map(IntoIterator
::into_iter
),
3936 fn size_hint(&self) -> (usize, Option
<usize>) {
3937 let (flo
, fhi
) = self.frontiter
.as_ref().map_or((0, Some(0)), |it
| it
.size_hint());
3938 let (blo
, bhi
) = self.backiter
.as_ref().map_or((0, Some(0)), |it
| it
.size_hint());
3939 let lo
= flo
.saturating_add(blo
);
3940 match (self.iter
.size_hint(), fhi
, bhi
) {
3941 ((0, Some(0)), Some(a
), Some(b
)) => (lo
, a
.checked_add(b
)),
3947 #[stable(feature = "rust1", since = "1.0.0")]
3948 impl<I
: DoubleEndedIterator
, U
, F
> DoubleEndedIterator
for FlatMap
<I
, U
, F
> where
3949 F
: FnMut(I
::Item
) -> U
,
3951 U
::IntoIter
: DoubleEndedIterator
3954 fn next_back(&mut self) -> Option
<U
::Item
> {
3956 if let Some(ref mut inner
) = self.backiter
{
3957 if let Some(y
) = inner
.next_back() {
3961 match self.iter
.next_back().map(&mut self.f
) {
3962 None
=> return self.frontiter
.as_mut().and_then(|it
| it
.next_back()),
3963 next
=> self.backiter
= next
.map(IntoIterator
::into_iter
),
3969 /// An iterator that yields `None` forever after the underlying iterator
3970 /// yields `None` once.
3972 /// This `struct` is created by the [`fuse()`] method on [`Iterator`]. See its
3973 /// documentation for more.
3975 /// [`fuse()`]: trait.Iterator.html#method.fuse
3976 /// [`Iterator`]: trait.Iterator.html
3978 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3979 #[stable(feature = "rust1", since = "1.0.0")]
3980 pub struct Fuse
<I
> {
3985 #[stable(feature = "rust1", since = "1.0.0")]
3986 impl<I
> Iterator
for Fuse
<I
> where I
: Iterator
{
3987 type Item
= <I
as Iterator
>::Item
;
3990 fn next(&mut self) -> Option
<<I
as Iterator
>::Item
> {
3994 let next
= self.iter
.next();
3995 self.done
= next
.is_none();
4001 fn nth(&mut self, n
: usize) -> Option
<I
::Item
> {
4005 let nth
= self.iter
.nth(n
);
4006 self.done
= nth
.is_none();
4012 fn last(self) -> Option
<I
::Item
> {
4021 fn count(self) -> usize {
4030 fn size_hint(&self) -> (usize, Option
<usize>) {
4034 self.iter
.size_hint()
4039 #[stable(feature = "rust1", since = "1.0.0")]
4040 impl<I
> DoubleEndedIterator
for Fuse
<I
> where I
: DoubleEndedIterator
{
4042 fn next_back(&mut self) -> Option
<<I
as Iterator
>::Item
> {
4046 let next
= self.iter
.next_back();
4047 self.done
= next
.is_none();
4053 #[stable(feature = "rust1", since = "1.0.0")]
4054 impl<I
> ExactSizeIterator
for Fuse
<I
> where I
: ExactSizeIterator {}
4056 /// An iterator that calls a function with a reference to each element before
4059 /// This `struct` is created by the [`inspect()`] method on [`Iterator`]. See its
4060 /// documentation for more.
4062 /// [`inspect()`]: trait.Iterator.html#method.inspect
4063 /// [`Iterator`]: trait.Iterator.html
4064 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
4065 #[stable(feature = "rust1", since = "1.0.0")]
4067 pub struct Inspect
<I
, F
> {
4072 impl<I
: Iterator
, F
> Inspect
<I
, F
> where F
: FnMut(&I
::Item
) {
4074 fn do_inspect(&mut self, elt
: Option
<I
::Item
>) -> Option
<I
::Item
> {
4075 if let Some(ref a
) = elt
{
4083 #[stable(feature = "rust1", since = "1.0.0")]
4084 impl<I
: Iterator
, F
> Iterator
for Inspect
<I
, F
> where F
: FnMut(&I
::Item
) {
4085 type Item
= I
::Item
;
4088 fn next(&mut self) -> Option
<I
::Item
> {
4089 let next
= self.iter
.next();
4090 self.do_inspect(next
)
4094 fn size_hint(&self) -> (usize, Option
<usize>) {
4095 self.iter
.size_hint()
4099 #[stable(feature = "rust1", since = "1.0.0")]
4100 impl<I
: DoubleEndedIterator
, F
> DoubleEndedIterator
for Inspect
<I
, F
>
4101 where F
: FnMut(&I
::Item
),
4104 fn next_back(&mut self) -> Option
<I
::Item
> {
4105 let next
= self.iter
.next_back();
4106 self.do_inspect(next
)
4110 /// Objects that can be stepped over in both directions.
4112 /// The `steps_between` function provides a way to efficiently compare
4113 /// two `Step` objects.
4114 #[unstable(feature = "step_trait",
4115 reason
= "likely to be replaced by finer-grained traits",
4117 pub trait Step
: PartialOrd
+ Sized
{
4118 /// Steps `self` if possible.
4119 fn step(&self, by
: &Self) -> Option
<Self>;
4121 /// Returns the number of steps between two step objects. The count is
4122 /// inclusive of `start` and exclusive of `end`.
4124 /// Returns `None` if it is not possible to calculate `steps_between`
4125 /// without overflow.
4126 fn steps_between(start
: &Self, end
: &Self, by
: &Self) -> Option
<usize>;
4129 macro_rules
! step_impl_unsigned
{
4131 #[unstable(feature = "step_trait",
4132 reason
= "likely to be replaced by finer-grained traits",
4136 fn step(&self, by
: &$t
) -> Option
<$t
> {
4137 (*self).checked_add(*by
)
4140 #[allow(trivial_numeric_casts)]
4141 fn steps_between(start
: &$t
, end
: &$t
, by
: &$t
) -> Option
<usize> {
4142 if *by
== 0 { return None; }
4144 // Note: We assume $t <= usize here
4145 let diff
= (*end
- *start
) as usize;
4146 let by
= *by
as usize;
4159 macro_rules
! step_impl_signed
{
4161 #[unstable(feature = "step_trait",
4162 reason
= "likely to be replaced by finer-grained traits",
4166 fn step(&self, by
: &$t
) -> Option
<$t
> {
4167 (*self).checked_add(*by
)
4170 #[allow(trivial_numeric_casts)]
4171 fn steps_between(start
: &$t
, end
: &$t
, by
: &$t
) -> Option
<usize> {
4172 if *by
== 0 { return None; }
4179 // Note: We assume $t <= isize here
4180 // Use .wrapping_sub and cast to usize to compute the
4181 // difference that may not fit inside the range of isize.
4182 diff
= (*end
as isize).wrapping_sub(*start
as isize) as usize;
4183 by_u
= *by
as usize;
4188 diff
= (*start
as isize).wrapping_sub(*end
as isize) as usize;
4189 by_u
= (*by
as isize).wrapping_mul(-1) as usize;
4191 if diff
% by_u
> 0 {
4192 Some(diff
/ by_u
+ 1)
4201 macro_rules
! step_impl_no_between
{
4203 #[unstable(feature = "step_trait",
4204 reason
= "likely to be replaced by finer-grained traits",
4208 fn step(&self, by
: &$t
) -> Option
<$t
> {
4209 (*self).checked_add(*by
)
4212 fn steps_between(_a
: &$t
, _b
: &$t
, _by
: &$t
) -> Option
<usize> {
4219 step_impl_unsigned
!(usize u8 u16 u32);
4220 step_impl_signed
!(isize i8 i16 i32);
4221 #[cfg(target_pointer_width = "64")]
4222 step_impl_unsigned
!(u64);
4223 #[cfg(target_pointer_width = "64")]
4224 step_impl_signed
!(i64);
4225 // If the target pointer width is not 64-bits, we
4226 // assume here that it is less than 64-bits.
4227 #[cfg(not(target_pointer_width = "64"))]
4228 step_impl_no_between
!(u64 i64);
4230 /// An adapter for stepping range iterators by a custom amount.
4232 /// The resulting iterator handles overflow by stopping. The `A`
4233 /// parameter is the type being iterated over, while `R` is the range
4234 /// type (usually one of `std::ops::{Range, RangeFrom}`.
4236 #[unstable(feature = "step_by", reason = "recent addition",
4238 pub struct StepBy
<A
, R
> {
4243 impl<A
: Step
> RangeFrom
<A
> {
4244 /// Creates an iterator starting at the same point, but stepping by
4245 /// the given amount at each iteration.
4250 /// for i in (0u8..).step_by(2) {
4251 /// println!("{}", i);
4255 /// This prints all even `u8` values.
4256 #[unstable(feature = "step_by", reason = "recent addition",
4258 pub fn step_by(self, by
: A
) -> StepBy
<A
, Self> {
4266 impl<A
: Step
> ops
::Range
<A
> {
4267 /// Creates an iterator with the same range, but stepping by the
4268 /// given amount at each iteration.
4270 /// The resulting iterator handles overflow by stopping.
4275 /// #![feature(step_by)]
4277 /// for i in (0..10).step_by(2) {
4278 /// println!("{}", i);
4291 #[unstable(feature = "step_by", reason = "recent addition",
4293 pub fn step_by(self, by
: A
) -> StepBy
<A
, Self> {
4301 #[stable(feature = "rust1", since = "1.0.0")]
4302 impl<A
> Iterator
for StepBy
<A
, RangeFrom
<A
>> where
4304 for<'a
> &'a A
: Add
<&'a A
, Output
= A
>
4309 fn next(&mut self) -> Option
<A
> {
4310 let mut n
= &self.range
.start
+ &self.step_by
;
4311 mem
::swap(&mut n
, &mut self.range
.start
);
4316 fn size_hint(&self) -> (usize, Option
<usize>) {
4317 (usize::MAX
, None
) // Too bad we can't specify an infinite lower bound
4321 /// An iterator over the range [start, stop]
4323 #[unstable(feature = "range_inclusive",
4324 reason
= "likely to be replaced by range notation and adapters",
4326 #[rustc_deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4327 #[allow(deprecated)]
4328 pub struct RangeInclusive
<A
> {
4329 range
: ops
::Range
<A
>,
4333 /// Returns an iterator over the range [start, stop].
4335 #[unstable(feature = "range_inclusive",
4336 reason
= "likely to be replaced by range notation and adapters",
4338 #[rustc_deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4339 #[allow(deprecated)]
4340 pub fn range_inclusive
<A
>(start
: A
, stop
: A
) -> RangeInclusive
<A
>
4341 where A
: Step
+ One
+ Clone
4349 #[unstable(feature = "range_inclusive",
4350 reason
= "likely to be replaced by range notation and adapters",
4352 #[rustc_deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4353 #[allow(deprecated)]
4354 impl<A
> Iterator
for RangeInclusive
<A
> where
4355 A
: PartialEq
+ Step
+ One
+ Clone
,
4356 for<'a
> &'a A
: Add
<&'a A
, Output
= A
>
4361 fn next(&mut self) -> Option
<A
> {
4362 self.range
.next().or_else(|| {
4363 if !self.done
&& self.range
.start
== self.range
.end
{
4365 Some(self.range
.end
.clone())
4373 fn size_hint(&self) -> (usize, Option
<usize>) {
4374 let (lo
, hi
) = self.range
.size_hint();
4378 let lo
= lo
.saturating_add(1);
4379 let hi
= hi
.and_then(|x
| x
.checked_add(1));
4385 #[unstable(feature = "range_inclusive",
4386 reason
= "likely to be replaced by range notation and adapters",
4388 #[rustc_deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4389 #[allow(deprecated)]
4390 impl<A
> DoubleEndedIterator
for RangeInclusive
<A
> where
4391 A
: PartialEq
+ Step
+ One
+ Clone
,
4392 for<'a
> &'a A
: Add
<&'a A
, Output
= A
>,
4393 for<'a
> &'a A
: Sub
<Output
=A
>
4396 fn next_back(&mut self) -> Option
<A
> {
4397 if self.range
.end
> self.range
.start
{
4398 let result
= self.range
.end
.clone();
4399 self.range
.end
= &self.range
.end
- &A
::one();
4401 } else if !self.done
&& self.range
.start
== self.range
.end
{
4403 Some(self.range
.end
.clone())
4410 #[stable(feature = "rust1", since = "1.0.0")]
4411 impl<A
: Step
+ Zero
+ Clone
> Iterator
for StepBy
<A
, ops
::Range
<A
>> {
4415 fn next(&mut self) -> Option
<A
> {
4416 let rev
= self.step_by
< A
::zero();
4417 if (rev
&& self.range
.start
> self.range
.end
) ||
4418 (!rev
&& self.range
.start
< self.range
.end
)
4420 match self.range
.start
.step(&self.step_by
) {
4422 mem
::swap(&mut self.range
.start
, &mut n
);
4426 let mut n
= self.range
.end
.clone();
4427 mem
::swap(&mut self.range
.start
, &mut n
);
4437 fn size_hint(&self) -> (usize, Option
<usize>) {
4438 match Step
::steps_between(&self.range
.start
,
4441 Some(hint
) => (hint
, Some(hint
)),
4447 macro_rules
! range_exact_iter_impl
{
4449 #[stable(feature = "rust1", since = "1.0.0")]
4450 impl ExactSizeIterator
for ops
::Range
<$t
> { }
4454 #[stable(feature = "rust1", since = "1.0.0")]
4455 impl<A
: Step
+ One
> Iterator
for ops
::Range
<A
> where
4456 for<'a
> &'a A
: Add
<&'a A
, Output
= A
>
4461 fn next(&mut self) -> Option
<A
> {
4462 if self.start
< self.end
{
4463 let mut n
= &self.start
+ &A
::one();
4464 mem
::swap(&mut n
, &mut self.start
);
4472 fn size_hint(&self) -> (usize, Option
<usize>) {
4473 match Step
::steps_between(&self.start
, &self.end
, &A
::one()) {
4474 Some(hint
) => (hint
, Some(hint
)),
4480 // Ranges of u64 and i64 are excluded because they cannot guarantee having
4481 // a length <= usize::MAX, which is required by ExactSizeIterator.
4482 range_exact_iter_impl
!(usize u8 u16 u32 isize i8 i16 i32);
4484 #[stable(feature = "rust1", since = "1.0.0")]
4485 impl<A
: Step
+ One
+ Clone
> DoubleEndedIterator
for ops
::Range
<A
> where
4486 for<'a
> &'a A
: Add
<&'a A
, Output
= A
>,
4487 for<'a
> &'a A
: Sub
<&'a A
, Output
= A
>
4490 fn next_back(&mut self) -> Option
<A
> {
4491 if self.start
< self.end
{
4492 self.end
= &self.end
- &A
::one();
4493 Some(self.end
.clone())
4500 #[stable(feature = "rust1", since = "1.0.0")]
4501 impl<A
: Step
+ One
> Iterator
for ops
::RangeFrom
<A
> where
4502 for<'a
> &'a A
: Add
<&'a A
, Output
= A
>
4507 fn next(&mut self) -> Option
<A
> {
4508 let mut n
= &self.start
+ &A
::one();
4509 mem
::swap(&mut n
, &mut self.start
);
4514 /// An iterator that repeats an element endlessly.
4516 /// This `struct` is created by the [`repeat()`] function. See its documentation for more.
4518 /// [`repeat()`]: fn.repeat.html
4520 #[stable(feature = "rust1", since = "1.0.0")]
4521 pub struct Repeat
<A
> {
4525 #[stable(feature = "rust1", since = "1.0.0")]
4526 impl<A
: Clone
> Iterator
for Repeat
<A
> {
4530 fn next(&mut self) -> Option
<A
> { Some(self.element.clone()) }
4532 fn size_hint(&self) -> (usize, Option
<usize>) { (usize::MAX, None) }
4535 #[stable(feature = "rust1", since = "1.0.0")]
4536 impl<A
: Clone
> DoubleEndedIterator
for Repeat
<A
> {
4538 fn next_back(&mut self) -> Option
<A
> { Some(self.element.clone()) }
4541 /// Creates a new iterator that endlessly repeats a single element.
4543 /// The `repeat()` function repeats a single value over and over and over and
4544 /// over and over and 🔁.
4546 /// Infinite iterators like `repeat()` are often used with adapters like
4547 /// [`take()`], in order to make them finite.
4549 /// [`take()`]: trait.Iterator.html#method.take
4558 /// // the number four 4ever:
4559 /// let mut fours = iter::repeat(4);
4561 /// assert_eq!(Some(4), fours.next());
4562 /// assert_eq!(Some(4), fours.next());
4563 /// assert_eq!(Some(4), fours.next());
4564 /// assert_eq!(Some(4), fours.next());
4565 /// assert_eq!(Some(4), fours.next());
4567 /// // yup, still four
4568 /// assert_eq!(Some(4), fours.next());
4571 /// Going finite with [`take()`]:
4576 /// // that last example was too many fours. Let's only have four fours.
4577 /// let mut four_fours = iter::repeat(4).take(4);
4579 /// assert_eq!(Some(4), four_fours.next());
4580 /// assert_eq!(Some(4), four_fours.next());
4581 /// assert_eq!(Some(4), four_fours.next());
4582 /// assert_eq!(Some(4), four_fours.next());
4584 /// // ... and now we're done
4585 /// assert_eq!(None, four_fours.next());
4588 #[stable(feature = "rust1", since = "1.0.0")]
4589 pub fn repeat
<T
: Clone
>(elt
: T
) -> Repeat
<T
> {
4590 Repeat{element: elt}
4593 /// An iterator that yields nothing.
4595 /// This `struct` is created by the [`empty()`] function. See its documentation for more.
4597 /// [`empty()`]: fn.empty.html
4598 #[stable(feature = "iter_empty", since = "1.2.0")]
4599 pub struct Empty
<T
>(marker
::PhantomData
<T
>);
4601 #[stable(feature = "iter_empty", since = "1.2.0")]
4602 impl<T
> Iterator
for Empty
<T
> {
4605 fn next(&mut self) -> Option
<T
> {
4609 fn size_hint(&self) -> (usize, Option
<usize>){
4614 #[stable(feature = "iter_empty", since = "1.2.0")]
4615 impl<T
> DoubleEndedIterator
for Empty
<T
> {
4616 fn next_back(&mut self) -> Option
<T
> {
4621 #[stable(feature = "iter_empty", since = "1.2.0")]
4622 impl<T
> ExactSizeIterator
for Empty
<T
> {
4623 fn len(&self) -> usize {
4628 // not #[derive] because that adds a Clone bound on T,
4629 // which isn't necessary.
4630 #[stable(feature = "iter_empty", since = "1.2.0")]
4631 impl<T
> Clone
for Empty
<T
> {
4632 fn clone(&self) -> Empty
<T
> {
4633 Empty(marker
::PhantomData
)
4637 // not #[derive] because that adds a Default bound on T,
4638 // which isn't necessary.
4639 #[stable(feature = "iter_empty", since = "1.2.0")]
4640 impl<T
> Default
for Empty
<T
> {
4641 fn default() -> Empty
<T
> {
4642 Empty(marker
::PhantomData
)
4646 /// Creates an iterator that yields nothing.
4655 /// // this could have been an iterator over i32, but alas, it's just not.
4656 /// let mut nope = iter::empty::<i32>();
4658 /// assert_eq!(None, nope.next());
4660 #[stable(feature = "iter_empty", since = "1.2.0")]
4661 pub fn empty
<T
>() -> Empty
<T
> {
4662 Empty(marker
::PhantomData
)
4665 /// An iterator that yields an element exactly once.
4667 /// This `struct` is created by the [`once()`] function. See its documentation for more.
4669 /// [`once()`]: fn.once.html
4671 #[stable(feature = "iter_once", since = "1.2.0")]
4672 pub struct Once
<T
> {
4673 inner
: ::option
::IntoIter
<T
>
4676 #[stable(feature = "iter_once", since = "1.2.0")]
4677 impl<T
> Iterator
for Once
<T
> {
4680 fn next(&mut self) -> Option
<T
> {
4684 fn size_hint(&self) -> (usize, Option
<usize>) {
4685 self.inner
.size_hint()
4689 #[stable(feature = "iter_once", since = "1.2.0")]
4690 impl<T
> DoubleEndedIterator
for Once
<T
> {
4691 fn next_back(&mut self) -> Option
<T
> {
4692 self.inner
.next_back()
4696 #[stable(feature = "iter_once", since = "1.2.0")]
4697 impl<T
> ExactSizeIterator
for Once
<T
> {
4698 fn len(&self) -> usize {
4703 /// Creates an iterator that yields an element exactly once.
4705 /// This is commonly used to adapt a single value into a [`chain()`] of other
4706 /// kinds of iteration. Maybe you have an iterator that covers almost
4707 /// everything, but you need an extra special case. Maybe you have a function
4708 /// which works on iterators, but you only need to process one value.
4710 /// [`chain()`]: trait.Iterator.html#method.chain
4719 /// // one is the loneliest number
4720 /// let mut one = iter::once(1);
4722 /// assert_eq!(Some(1), one.next());
4724 /// // just one, that's all we get
4725 /// assert_eq!(None, one.next());
4728 /// Chaining together with another iterator. Let's say that we want to iterate
4729 /// over each file of the `.foo` directory, but also a configuration file,
4735 /// use std::path::PathBuf;
4737 /// let dirs = fs::read_dir(".foo").unwrap();
4739 /// // we need to convert from an iterator of DirEntry-s to an iterator of
4740 /// // PathBufs, so we use map
4741 /// let dirs = dirs.map(|file| file.unwrap().path());
4743 /// // now, our iterator just for our config file
4744 /// let config = iter::once(PathBuf::from(".foorc"));
4746 /// // chain the two iterators together into one big iterator
4747 /// let files = dirs.chain(config);
4749 /// // this will give us all of the files in .foo as well as .foorc
4750 /// for f in files {
4751 /// println!("{:?}", f);
4754 #[stable(feature = "iter_once", since = "1.2.0")]
4755 pub fn once
<T
>(value
: T
) -> Once
<T
> {
4756 Once { inner: Some(value).into_iter() }