1 // Copyright 2013-2016 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.
14 use super::{AlwaysOk, LoopState};
15 use super::{Chain, Cycle, Cloned, Enumerate, Filter, FilterMap, Fuse};
16 use super::{Flatten, FlatMap, flatten_compat};
17 use super::{Inspect, Map, Peekable, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile, Rev};
18 use super::{Zip, Sum, Product};
19 use super::{ChainState, FromIterator, ZipImpl};
21 fn _assert_is_object_safe(_: &Iterator<Item=()>) {}
23 /// An interface for dealing with iterators.
25 /// This is the main iterator trait. For more about the concept of iterators
26 /// generally, please see the [module-level documentation]. In particular, you
27 /// may want to know how to [implement `Iterator`][impl].
29 /// [module-level documentation]: index.html
30 /// [impl]: index.html#implementing-iterator
31 #[stable(feature = "rust1", since = "1.0.0")]
32 #[rustc_on_unimplemented(
35 label="`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
37 label="`{Self}` is not an iterator; maybe try calling `.iter()` or a similar method"
41 /// The type of the elements being iterated over.
42 #[stable(feature = "rust1", since = "1.0.0")]
45 /// Advances the iterator and returns the next value.
47 /// Returns [`None`] when iteration is finished. Individual iterator
48 /// implementations may choose to resume iteration, and so calling `next()`
49 /// again may or may not eventually start returning [`Some(Item)`] again at some
52 /// [`None`]: ../../std/option/enum.Option.html#variant.None
53 /// [`Some(Item)`]: ../../std/option/enum.Option.html#variant.Some
60 /// let a = [1, 2, 3];
62 /// let mut iter = a.iter();
64 /// // A call to next() returns the next value...
65 /// assert_eq!(Some(&1), iter.next());
66 /// assert_eq!(Some(&2), iter.next());
67 /// assert_eq!(Some(&3), iter.next());
69 /// // ... and then None once it's over.
70 /// assert_eq!(None, iter.next());
72 /// // More calls may or may not return None. Here, they always will.
73 /// assert_eq!(None, iter.next());
74 /// assert_eq!(None, iter.next());
76 #[stable(feature = "rust1", since = "1.0.0")]
77 fn next(&mut self) -> Option<Self::Item>;
79 /// Returns the bounds on the remaining length of the iterator.
81 /// Specifically, `size_hint()` returns a tuple where the first element
82 /// is the lower bound, and the second element is the upper bound.
84 /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
85 /// A [`None`] here means that either there is no known upper bound, or the
86 /// upper bound is larger than [`usize`].
88 /// # Implementation notes
90 /// It is not enforced that an iterator implementation yields the declared
91 /// number of elements. A buggy iterator may yield less than the lower bound
92 /// or more than the upper bound of elements.
94 /// `size_hint()` is primarily intended to be used for optimizations such as
95 /// reserving space for the elements of the iterator, but must not be
96 /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
97 /// implementation of `size_hint()` should not lead to memory safety
100 /// That said, the implementation should provide a correct estimation,
101 /// because otherwise it would be a violation of the trait's protocol.
103 /// The default implementation returns `(0, None)` which is correct for any
106 /// [`usize`]: ../../std/primitive.usize.html
107 /// [`Option`]: ../../std/option/enum.Option.html
108 /// [`None`]: ../../std/option/enum.Option.html#variant.None
115 /// let a = [1, 2, 3];
116 /// let iter = a.iter();
118 /// assert_eq!((3, Some(3)), iter.size_hint());
121 /// A more complex example:
124 /// // The even numbers from zero to ten.
125 /// let iter = (0..10).filter(|x| x % 2 == 0);
127 /// // We might iterate from zero to ten times. Knowing that it's five
128 /// // exactly wouldn't be possible without executing filter().
129 /// assert_eq!((0, Some(10)), iter.size_hint());
131 /// // Let's add five more numbers with chain()
132 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
134 /// // now both bounds are increased by five
135 /// assert_eq!((5, Some(15)), iter.size_hint());
138 /// Returning `None` for an upper bound:
141 /// // an infinite iterator has no upper bound
142 /// // and the maximum possible lower bound
145 /// assert_eq!((usize::max_value(), None), iter.size_hint());
148 #[stable(feature = "rust1", since = "1.0.0")]
149 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
151 /// Consumes the iterator, counting the number of iterations and returning it.
153 /// This method will evaluate the iterator until its [`next`] returns
154 /// [`None`]. Once [`None`] is encountered, `count()` returns the number of
155 /// times it called [`next`].
157 /// [`next`]: #tymethod.next
158 /// [`None`]: ../../std/option/enum.Option.html#variant.None
160 /// # Overflow Behavior
162 /// The method does no guarding against overflows, so counting elements of
163 /// an iterator with more than [`usize::MAX`] elements either produces the
164 /// wrong result or panics. If debug assertions are enabled, a panic is
169 /// This function might panic if the iterator has more than [`usize::MAX`]
172 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
179 /// let a = [1, 2, 3];
180 /// assert_eq!(a.iter().count(), 3);
182 /// let a = [1, 2, 3, 4, 5];
183 /// assert_eq!(a.iter().count(), 5);
186 #[rustc_inherit_overflow_checks]
187 #[stable(feature = "rust1", since = "1.0.0")]
188 fn count(self) -> usize where Self: Sized {
190 self.fold(0, |cnt, _| cnt + 1)
193 /// Consumes the iterator, returning the last element.
195 /// This method will evaluate the iterator until it returns [`None`]. While
196 /// doing so, it keeps track of the current element. After [`None`] is
197 /// returned, `last()` will then return the last element it saw.
199 /// [`None`]: ../../std/option/enum.Option.html#variant.None
206 /// let a = [1, 2, 3];
207 /// assert_eq!(a.iter().last(), Some(&3));
209 /// let a = [1, 2, 3, 4, 5];
210 /// assert_eq!(a.iter().last(), Some(&5));
213 #[stable(feature = "rust1", since = "1.0.0")]
214 fn last(self) -> Option<Self::Item> where Self: Sized {
216 for x in self { last = Some(x); }
220 /// Returns the `n`th element of the iterator.
222 /// Like most indexing operations, the count starts from zero, so `nth(0)`
223 /// returns the first value, `nth(1)` the second, and so on.
225 /// Note that all preceding elements, as well as the returned element, will be
226 /// consumed from the iterator. That means that the preceding elements will be
227 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
228 /// will return different elements.
230 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
233 /// [`None`]: ../../std/option/enum.Option.html#variant.None
240 /// let a = [1, 2, 3];
241 /// assert_eq!(a.iter().nth(1), Some(&2));
244 /// Calling `nth()` multiple times doesn't rewind the iterator:
247 /// let a = [1, 2, 3];
249 /// let mut iter = a.iter();
251 /// assert_eq!(iter.nth(1), Some(&2));
252 /// assert_eq!(iter.nth(1), None);
255 /// Returning `None` if there are less than `n + 1` elements:
258 /// let a = [1, 2, 3];
259 /// assert_eq!(a.iter().nth(10), None);
262 #[stable(feature = "rust1", since = "1.0.0")]
263 fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
265 if n == 0 { return Some(x) }
271 /// Creates an iterator starting at the same point, but stepping by
272 /// the given amount at each iteration.
274 /// Note that it will always return the first element of the iterator,
275 /// regardless of the step given.
279 /// The method will panic if the given step is `0`.
286 /// #![feature(iterator_step_by)]
287 /// let a = [0, 1, 2, 3, 4, 5];
288 /// let mut iter = a.into_iter().step_by(2);
290 /// assert_eq!(iter.next(), Some(&0));
291 /// assert_eq!(iter.next(), Some(&2));
292 /// assert_eq!(iter.next(), Some(&4));
293 /// assert_eq!(iter.next(), None);
296 #[unstable(feature = "iterator_step_by",
297 reason = "unstable replacement of Range::step_by",
299 fn step_by(self, step: usize) -> StepBy<Self> where Self: Sized {
301 StepBy{iter: self, step: step - 1, first_take: true}
304 /// Takes two iterators and creates a new iterator over both in sequence.
306 /// `chain()` will return a new iterator which will first iterate over
307 /// values from the first iterator and then over values from the second
310 /// In other words, it links two iterators together, in a chain. 🔗
317 /// let a1 = [1, 2, 3];
318 /// let a2 = [4, 5, 6];
320 /// let mut iter = a1.iter().chain(a2.iter());
322 /// assert_eq!(iter.next(), Some(&1));
323 /// assert_eq!(iter.next(), Some(&2));
324 /// assert_eq!(iter.next(), Some(&3));
325 /// assert_eq!(iter.next(), Some(&4));
326 /// assert_eq!(iter.next(), Some(&5));
327 /// assert_eq!(iter.next(), Some(&6));
328 /// assert_eq!(iter.next(), None);
331 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
332 /// anything that can be converted into an [`Iterator`], not just an
333 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
334 /// [`IntoIterator`], and so can be passed to `chain()` directly:
336 /// [`IntoIterator`]: trait.IntoIterator.html
337 /// [`Iterator`]: trait.Iterator.html
340 /// let s1 = &[1, 2, 3];
341 /// let s2 = &[4, 5, 6];
343 /// let mut iter = s1.iter().chain(s2);
345 /// assert_eq!(iter.next(), Some(&1));
346 /// assert_eq!(iter.next(), Some(&2));
347 /// assert_eq!(iter.next(), Some(&3));
348 /// assert_eq!(iter.next(), Some(&4));
349 /// assert_eq!(iter.next(), Some(&5));
350 /// assert_eq!(iter.next(), Some(&6));
351 /// assert_eq!(iter.next(), None);
354 #[stable(feature = "rust1", since = "1.0.0")]
355 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
356 Self: Sized, U: IntoIterator<Item=Self::Item>,
358 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
361 /// 'Zips up' two iterators into a single iterator of pairs.
363 /// `zip()` returns a new iterator that will iterate over two other
364 /// iterators, returning a tuple where the first element comes from the
365 /// first iterator, and the second element comes from the second iterator.
367 /// In other words, it zips two iterators together, into a single one.
369 /// When either iterator returns [`None`], all further calls to [`next`]
370 /// will return [`None`].
377 /// let a1 = [1, 2, 3];
378 /// let a2 = [4, 5, 6];
380 /// let mut iter = a1.iter().zip(a2.iter());
382 /// assert_eq!(iter.next(), Some((&1, &4)));
383 /// assert_eq!(iter.next(), Some((&2, &5)));
384 /// assert_eq!(iter.next(), Some((&3, &6)));
385 /// assert_eq!(iter.next(), None);
388 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
389 /// anything that can be converted into an [`Iterator`], not just an
390 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
391 /// [`IntoIterator`], and so can be passed to `zip()` directly:
393 /// [`IntoIterator`]: trait.IntoIterator.html
394 /// [`Iterator`]: trait.Iterator.html
397 /// let s1 = &[1, 2, 3];
398 /// let s2 = &[4, 5, 6];
400 /// let mut iter = s1.iter().zip(s2);
402 /// assert_eq!(iter.next(), Some((&1, &4)));
403 /// assert_eq!(iter.next(), Some((&2, &5)));
404 /// assert_eq!(iter.next(), Some((&3, &6)));
405 /// assert_eq!(iter.next(), None);
408 /// `zip()` is often used to zip an infinite iterator to a finite one.
409 /// This works because the finite iterator will eventually return [`None`],
410 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
413 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
415 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
417 /// assert_eq!((0, 'f'), enumerate[0]);
418 /// assert_eq!((0, 'f'), zipper[0]);
420 /// assert_eq!((1, 'o'), enumerate[1]);
421 /// assert_eq!((1, 'o'), zipper[1]);
423 /// assert_eq!((2, 'o'), enumerate[2]);
424 /// assert_eq!((2, 'o'), zipper[2]);
427 /// [`enumerate`]: trait.Iterator.html#method.enumerate
428 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
429 /// [`None`]: ../../std/option/enum.Option.html#variant.None
431 #[stable(feature = "rust1", since = "1.0.0")]
432 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
433 Self: Sized, U: IntoIterator
435 Zip::new(self, other.into_iter())
438 /// Takes a closure and creates an iterator which calls that closure on each
441 /// `map()` transforms one iterator into another, by means of its argument:
442 /// something that implements `FnMut`. It produces a new iterator which
443 /// calls this closure on each element of the original iterator.
445 /// If you are good at thinking in types, you can think of `map()` like this:
446 /// If you have an iterator that gives you elements of some type `A`, and
447 /// you want an iterator of some other type `B`, you can use `map()`,
448 /// passing a closure that takes an `A` and returns a `B`.
450 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
451 /// lazy, it is best used when you're already working with other iterators.
452 /// If you're doing some sort of looping for a side effect, it's considered
453 /// more idiomatic to use [`for`] than `map()`.
455 /// [`for`]: ../../book/first-edition/loops.html#for
462 /// let a = [1, 2, 3];
464 /// let mut iter = a.into_iter().map(|x| 2 * x);
466 /// assert_eq!(iter.next(), Some(2));
467 /// assert_eq!(iter.next(), Some(4));
468 /// assert_eq!(iter.next(), Some(6));
469 /// assert_eq!(iter.next(), None);
472 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
475 /// # #![allow(unused_must_use)]
476 /// // don't do this:
477 /// (0..5).map(|x| println!("{}", x));
479 /// // it won't even execute, as it is lazy. Rust will warn you about this.
481 /// // Instead, use for:
483 /// println!("{}", x);
487 #[stable(feature = "rust1", since = "1.0.0")]
488 fn map<B, F>(self, f: F) -> Map<Self, F> where
489 Self: Sized, F: FnMut(Self::Item) -> B,
491 Map{iter: self, f: f}
494 /// Calls a closure on each element of an iterator.
496 /// This is equivalent to using a [`for`] loop on the iterator, although
497 /// `break` and `continue` are not possible from a closure. It's generally
498 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
499 /// when processing items at the end of longer iterator chains. In some
500 /// cases `for_each` may also be faster than a loop, because it will use
501 /// internal iteration on adaptors like `Chain`.
503 /// [`for`]: ../../book/first-edition/loops.html#for
510 /// use std::sync::mpsc::channel;
512 /// let (tx, rx) = channel();
513 /// (0..5).map(|x| x * 2 + 1)
514 /// .for_each(move |x| tx.send(x).unwrap());
516 /// let v: Vec<_> = rx.iter().collect();
517 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
520 /// For such a small example, a `for` loop may be cleaner, but `for_each`
521 /// might be preferable to keep a functional style with longer iterators:
524 /// (0..5).flat_map(|x| x * 100 .. x * 110)
526 /// .filter(|&(i, x)| (i + x) % 3 == 0)
527 /// .for_each(|(i, x)| println!("{}:{}", i, x));
530 #[stable(feature = "iterator_for_each", since = "1.21.0")]
531 fn for_each<F>(self, mut f: F) where
532 Self: Sized, F: FnMut(Self::Item),
534 self.fold((), move |(), item| f(item));
537 /// Creates an iterator which uses a closure to determine if an element
538 /// should be yielded.
540 /// The closure must return `true` or `false`. `filter()` creates an
541 /// iterator which calls this closure on each element. If the closure
542 /// returns `true`, then the element is returned. If the closure returns
543 /// `false`, it will try again, and call the closure on the next element,
544 /// seeing if it passes the test.
551 /// let a = [0i32, 1, 2];
553 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
555 /// assert_eq!(iter.next(), Some(&1));
556 /// assert_eq!(iter.next(), Some(&2));
557 /// assert_eq!(iter.next(), None);
560 /// Because the closure passed to `filter()` takes a reference, and many
561 /// iterators iterate over references, this leads to a possibly confusing
562 /// situation, where the type of the closure is a double reference:
565 /// let a = [0, 1, 2];
567 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
569 /// assert_eq!(iter.next(), Some(&2));
570 /// assert_eq!(iter.next(), None);
573 /// It's common to instead use destructuring on the argument to strip away
577 /// let a = [0, 1, 2];
579 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
581 /// assert_eq!(iter.next(), Some(&2));
582 /// assert_eq!(iter.next(), None);
588 /// let a = [0, 1, 2];
590 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
592 /// assert_eq!(iter.next(), Some(&2));
593 /// assert_eq!(iter.next(), None);
598 #[stable(feature = "rust1", since = "1.0.0")]
599 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
600 Self: Sized, P: FnMut(&Self::Item) -> bool,
602 Filter{iter: self, predicate: predicate}
605 /// Creates an iterator that both filters and maps.
607 /// The closure must return an [`Option<T>`]. `filter_map` creates an
608 /// iterator which calls this closure on each element. If the closure
609 /// returns [`Some(element)`][`Some`], then that element is returned. If the
610 /// closure returns [`None`], it will try again, and call the closure on the
611 /// next element, seeing if it will return [`Some`].
613 /// Why `filter_map` and not just [`filter`] and [`map`]? The key is in this
616 /// [`filter`]: #method.filter
617 /// [`map`]: #method.map
619 /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
621 /// In other words, it removes the [`Option<T>`] layer automatically. If your
622 /// mapping is already returning an [`Option<T>`] and you want to skip over
623 /// [`None`]s, then `filter_map` is much, much nicer to use.
630 /// let a = ["1", "lol", "3", "NaN", "5"];
632 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
634 /// assert_eq!(iter.next(), Some(1));
635 /// assert_eq!(iter.next(), Some(3));
636 /// assert_eq!(iter.next(), Some(5));
637 /// assert_eq!(iter.next(), None);
640 /// Here's the same example, but with [`filter`] and [`map`]:
643 /// let a = ["1", "lol", "3", "NaN", "5"];
644 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
645 /// assert_eq!(iter.next(), Some(1));
646 /// assert_eq!(iter.next(), Some(3));
647 /// assert_eq!(iter.next(), Some(5));
648 /// assert_eq!(iter.next(), None);
651 /// [`Option<T>`]: ../../std/option/enum.Option.html
652 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
653 /// [`None`]: ../../std/option/enum.Option.html#variant.None
655 #[stable(feature = "rust1", since = "1.0.0")]
656 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
657 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
659 FilterMap { iter: self, f: f }
662 /// Creates an iterator which gives the current iteration count as well as
665 /// The iterator returned yields pairs `(i, val)`, where `i` is the
666 /// current index of iteration and `val` is the value returned by the
669 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
670 /// different sized integer, the [`zip`] function provides similar
673 /// # Overflow Behavior
675 /// The method does no guarding against overflows, so enumerating more than
676 /// [`usize::MAX`] elements either produces the wrong result or panics. If
677 /// debug assertions are enabled, a panic is guaranteed.
681 /// The returned iterator might panic if the to-be-returned index would
682 /// overflow a [`usize`].
684 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
685 /// [`usize`]: ../../std/primitive.usize.html
686 /// [`zip`]: #method.zip
691 /// let a = ['a', 'b', 'c'];
693 /// let mut iter = a.iter().enumerate();
695 /// assert_eq!(iter.next(), Some((0, &'a')));
696 /// assert_eq!(iter.next(), Some((1, &'b')));
697 /// assert_eq!(iter.next(), Some((2, &'c')));
698 /// assert_eq!(iter.next(), None);
701 #[stable(feature = "rust1", since = "1.0.0")]
702 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
703 Enumerate { iter: self, count: 0 }
706 /// Creates an iterator which can use `peek` to look at the next element of
707 /// the iterator without consuming it.
709 /// Adds a [`peek`] method to an iterator. See its documentation for
710 /// more information.
712 /// Note that the underlying iterator is still advanced when [`peek`] is
713 /// called for the first time: In order to retrieve the next element,
714 /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
715 /// anything other than fetching the next value) of the [`next`] method
718 /// [`peek`]: struct.Peekable.html#method.peek
719 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
726 /// let xs = [1, 2, 3];
728 /// let mut iter = xs.iter().peekable();
730 /// // peek() lets us see into the future
731 /// assert_eq!(iter.peek(), Some(&&1));
732 /// assert_eq!(iter.next(), Some(&1));
734 /// assert_eq!(iter.next(), Some(&2));
736 /// // we can peek() multiple times, the iterator won't advance
737 /// assert_eq!(iter.peek(), Some(&&3));
738 /// assert_eq!(iter.peek(), Some(&&3));
740 /// assert_eq!(iter.next(), Some(&3));
742 /// // after the iterator is finished, so is peek()
743 /// assert_eq!(iter.peek(), None);
744 /// assert_eq!(iter.next(), None);
747 #[stable(feature = "rust1", since = "1.0.0")]
748 fn peekable(self) -> Peekable<Self> where Self: Sized {
749 Peekable{iter: self, peeked: None}
752 /// Creates an iterator that [`skip`]s elements based on a predicate.
754 /// [`skip`]: #method.skip
756 /// `skip_while()` takes a closure as an argument. It will call this
757 /// closure on each element of the iterator, and ignore elements
758 /// until it returns `false`.
760 /// After `false` is returned, `skip_while()`'s job is over, and the
761 /// rest of the elements are yielded.
768 /// let a = [-1i32, 0, 1];
770 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
772 /// assert_eq!(iter.next(), Some(&0));
773 /// assert_eq!(iter.next(), Some(&1));
774 /// assert_eq!(iter.next(), None);
777 /// Because the closure passed to `skip_while()` takes a reference, and many
778 /// iterators iterate over references, this leads to a possibly confusing
779 /// situation, where the type of the closure is a double reference:
782 /// let a = [-1, 0, 1];
784 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
786 /// assert_eq!(iter.next(), Some(&0));
787 /// assert_eq!(iter.next(), Some(&1));
788 /// assert_eq!(iter.next(), None);
791 /// Stopping after an initial `false`:
794 /// let a = [-1, 0, 1, -2];
796 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
798 /// assert_eq!(iter.next(), Some(&0));
799 /// assert_eq!(iter.next(), Some(&1));
801 /// // while this would have been false, since we already got a false,
802 /// // skip_while() isn't used any more
803 /// assert_eq!(iter.next(), Some(&-2));
805 /// assert_eq!(iter.next(), None);
808 #[stable(feature = "rust1", since = "1.0.0")]
809 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
810 Self: Sized, P: FnMut(&Self::Item) -> bool,
812 SkipWhile{iter: self, flag: false, predicate: predicate}
815 /// Creates an iterator that yields elements based on a predicate.
817 /// `take_while()` takes a closure as an argument. It will call this
818 /// closure on each element of the iterator, and yield elements
819 /// while it returns `true`.
821 /// After `false` is returned, `take_while()`'s job is over, and the
822 /// rest of the elements are ignored.
829 /// let a = [-1i32, 0, 1];
831 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
833 /// assert_eq!(iter.next(), Some(&-1));
834 /// assert_eq!(iter.next(), None);
837 /// Because the closure passed to `take_while()` takes a reference, and many
838 /// iterators iterate over references, this leads to a possibly confusing
839 /// situation, where the type of the closure is a double reference:
842 /// let a = [-1, 0, 1];
844 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
846 /// assert_eq!(iter.next(), Some(&-1));
847 /// assert_eq!(iter.next(), None);
850 /// Stopping after an initial `false`:
853 /// let a = [-1, 0, 1, -2];
855 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
857 /// assert_eq!(iter.next(), Some(&-1));
859 /// // We have more elements that are less than zero, but since we already
860 /// // got a false, take_while() isn't used any more
861 /// assert_eq!(iter.next(), None);
864 /// Because `take_while()` needs to look at the value in order to see if it
865 /// should be included or not, consuming iterators will see that it is
869 /// let a = [1, 2, 3, 4];
870 /// let mut iter = a.into_iter();
872 /// let result: Vec<i32> = iter.by_ref()
873 /// .take_while(|n| **n != 3)
877 /// assert_eq!(result, &[1, 2]);
879 /// let result: Vec<i32> = iter.cloned().collect();
881 /// assert_eq!(result, &[4]);
884 /// The `3` is no longer there, because it was consumed in order to see if
885 /// the iteration should stop, but wasn't placed back into the iterator or
886 /// some similar thing.
888 #[stable(feature = "rust1", since = "1.0.0")]
889 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
890 Self: Sized, P: FnMut(&Self::Item) -> bool,
892 TakeWhile{iter: self, flag: false, predicate: predicate}
895 /// Creates an iterator that skips the first `n` elements.
897 /// After they have been consumed, the rest of the elements are yielded.
904 /// let a = [1, 2, 3];
906 /// let mut iter = a.iter().skip(2);
908 /// assert_eq!(iter.next(), Some(&3));
909 /// assert_eq!(iter.next(), None);
912 #[stable(feature = "rust1", since = "1.0.0")]
913 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
914 Skip{iter: self, n: n}
917 /// Creates an iterator that yields its first `n` elements.
924 /// let a = [1, 2, 3];
926 /// let mut iter = a.iter().take(2);
928 /// assert_eq!(iter.next(), Some(&1));
929 /// assert_eq!(iter.next(), Some(&2));
930 /// assert_eq!(iter.next(), None);
933 /// `take()` is often used with an infinite iterator, to make it finite:
936 /// let mut iter = (0..).take(3);
938 /// assert_eq!(iter.next(), Some(0));
939 /// assert_eq!(iter.next(), Some(1));
940 /// assert_eq!(iter.next(), Some(2));
941 /// assert_eq!(iter.next(), None);
944 #[stable(feature = "rust1", since = "1.0.0")]
945 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
946 Take{iter: self, n: n}
949 /// An iterator adaptor similar to [`fold`] that holds internal state and
950 /// produces a new iterator.
952 /// [`fold`]: #method.fold
954 /// `scan()` takes two arguments: an initial value which seeds the internal
955 /// state, and a closure with two arguments, the first being a mutable
956 /// reference to the internal state and the second an iterator element.
957 /// The closure can assign to the internal state to share state between
960 /// On iteration, the closure will be applied to each element of the
961 /// iterator and the return value from the closure, an [`Option`], is
962 /// yielded by the iterator.
964 /// [`Option`]: ../../std/option/enum.Option.html
971 /// let a = [1, 2, 3];
973 /// let mut iter = a.iter().scan(1, |state, &x| {
974 /// // each iteration, we'll multiply the state by the element
975 /// *state = *state * x;
977 /// // the value passed on to the next iteration
981 /// assert_eq!(iter.next(), Some(1));
982 /// assert_eq!(iter.next(), Some(2));
983 /// assert_eq!(iter.next(), Some(6));
984 /// assert_eq!(iter.next(), None);
987 #[stable(feature = "rust1", since = "1.0.0")]
988 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
989 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
991 Scan{iter: self, f: f, state: initial_state}
994 /// Creates an iterator that works like map, but flattens nested structure.
996 /// The [`map`] adapter is very useful, but only when the closure
997 /// argument produces values. If it produces an iterator instead, there's
998 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1001 /// You can think of [`flat_map(f)`][flat_map] as the semantic equivalent
1002 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1004 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1005 /// one item for each element, and `flat_map()`'s closure returns an
1006 /// iterator for each element.
1008 /// [`map`]: #method.map
1009 /// [`flatten`]: #method.flatten
1016 /// let words = ["alpha", "beta", "gamma"];
1018 /// // chars() returns an iterator
1019 /// let merged: String = words.iter()
1020 /// .flat_map(|s| s.chars())
1022 /// assert_eq!(merged, "alphabetagamma");
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1027 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
1029 FlatMap { inner: flatten_compat(self.map(f)) }
1032 /// Creates an iterator that flattens nested structure.
1034 /// This is useful when you have an iterator of iterators or an iterator of
1035 /// things that can be turned into iterators and you want to remove one
1036 /// level of indirection.
1043 /// #![feature(iterator_flatten)]
1045 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1046 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1047 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1050 /// Mapping and then flattening:
1053 /// #![feature(iterator_flatten)]
1055 /// let words = ["alpha", "beta", "gamma"];
1057 /// // chars() returns an iterator
1058 /// let merged: String = words.iter()
1059 /// .map(|s| s.chars())
1062 /// assert_eq!(merged, "alphabetagamma");
1065 /// You can also rewrite this in terms of [`flat_map()`] which is preferable
1066 /// in this case since that conveys intent clearer:
1069 /// let words = ["alpha", "beta", "gamma"];
1071 /// // chars() returns an iterator
1072 /// let merged: String = words.iter()
1073 /// .flat_map(|s| s.chars())
1075 /// assert_eq!(merged, "alphabetagamma");
1078 /// Flattening once only removes one level of nesting:
1081 /// #![feature(iterator_flatten)]
1083 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1085 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1086 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1088 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1089 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1092 /// Here we see that `flatten()` does not perform a "deep" flatten.
1093 /// Instead, only one level of nesting is removed. That is, if you
1094 /// `flatten()` a three-dimensional array the result will be
1095 /// two-dimensional and not one-dimensional. To get a one-dimensional
1096 /// structure, you have to `flatten()` again.
1098 #[unstable(feature = "iterator_flatten", issue = "48213")]
1099 fn flatten(self) -> Flatten<Self>
1100 where Self: Sized, Self::Item: IntoIterator {
1101 Flatten { inner: flatten_compat(self) }
1104 /// Creates an iterator which ends after the first [`None`].
1106 /// After an iterator returns [`None`], future calls may or may not yield
1107 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1108 /// [`None`] is given, it will always return [`None`] forever.
1110 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1111 /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
1118 /// // an iterator which alternates between Some and None
1119 /// struct Alternate {
1123 /// impl Iterator for Alternate {
1124 /// type Item = i32;
1126 /// fn next(&mut self) -> Option<i32> {
1127 /// let val = self.state;
1128 /// self.state = self.state + 1;
1130 /// // if it's even, Some(i32), else None
1131 /// if val % 2 == 0 {
1139 /// let mut iter = Alternate { state: 0 };
1141 /// // we can see our iterator going back and forth
1142 /// assert_eq!(iter.next(), Some(0));
1143 /// assert_eq!(iter.next(), None);
1144 /// assert_eq!(iter.next(), Some(2));
1145 /// assert_eq!(iter.next(), None);
1147 /// // however, once we fuse it...
1148 /// let mut iter = iter.fuse();
1150 /// assert_eq!(iter.next(), Some(4));
1151 /// assert_eq!(iter.next(), None);
1153 /// // it will always return None after the first time.
1154 /// assert_eq!(iter.next(), None);
1155 /// assert_eq!(iter.next(), None);
1156 /// assert_eq!(iter.next(), None);
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 fn fuse(self) -> Fuse<Self> where Self: Sized {
1161 Fuse{iter: self, done: false}
1164 /// Do something with each element of an iterator, passing the value on.
1166 /// When using iterators, you'll often chain several of them together.
1167 /// While working on such code, you might want to check out what's
1168 /// happening at various parts in the pipeline. To do that, insert
1169 /// a call to `inspect()`.
1171 /// It's much more common for `inspect()` to be used as a debugging tool
1172 /// than to exist in your final code, but never say never.
1179 /// let a = [1, 4, 2, 3];
1181 /// // this iterator sequence is complex.
1182 /// let sum = a.iter()
1184 /// .filter(|&x| x % 2 == 0)
1185 /// .fold(0, |sum, i| sum + i);
1187 /// println!("{}", sum);
1189 /// // let's add some inspect() calls to investigate what's happening
1190 /// let sum = a.iter()
1192 /// .inspect(|x| println!("about to filter: {}", x))
1193 /// .filter(|&x| x % 2 == 0)
1194 /// .inspect(|x| println!("made it through filter: {}", x))
1195 /// .fold(0, |sum, i| sum + i);
1197 /// println!("{}", sum);
1200 /// This will print:
1203 /// about to filter: 1
1204 /// about to filter: 4
1205 /// made it through filter: 4
1206 /// about to filter: 2
1207 /// made it through filter: 2
1208 /// about to filter: 3
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1214 Self: Sized, F: FnMut(&Self::Item),
1216 Inspect{iter: self, f: f}
1219 /// Borrows an iterator, rather than consuming it.
1221 /// This is useful to allow applying iterator adaptors while still
1222 /// retaining ownership of the original iterator.
1229 /// let a = [1, 2, 3];
1231 /// let iter = a.into_iter();
1233 /// let sum: i32 = iter.take(5)
1234 /// .fold(0, |acc, &i| acc + i );
1236 /// assert_eq!(sum, 6);
1238 /// // if we try to use iter again, it won't work. The following line
1239 /// // gives "error: use of moved value: `iter`
1240 /// // assert_eq!(iter.next(), None);
1242 /// // let's try that again
1243 /// let a = [1, 2, 3];
1245 /// let mut iter = a.into_iter();
1247 /// // instead, we add in a .by_ref()
1248 /// let sum: i32 = iter.by_ref()
1250 /// .fold(0, |acc, &i| acc + i );
1252 /// assert_eq!(sum, 3);
1254 /// // now this is just fine:
1255 /// assert_eq!(iter.next(), Some(&3));
1256 /// assert_eq!(iter.next(), None);
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1261 /// Transforms an iterator into a collection.
1263 /// `collect()` can take anything iterable, and turn it into a relevant
1264 /// collection. This is one of the more powerful methods in the standard
1265 /// library, used in a variety of contexts.
1267 /// The most basic pattern in which `collect()` is used is to turn one
1268 /// collection into another. You take a collection, call [`iter`] on it,
1269 /// do a bunch of transformations, and then `collect()` at the end.
1271 /// One of the keys to `collect()`'s power is that many things you might
1272 /// not think of as 'collections' actually are. For example, a [`String`]
1273 /// is a collection of [`char`]s. And a collection of
1274 /// [`Result<T, E>`][`Result`] can be thought of as single
1275 /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1277 /// Because `collect()` is so general, it can cause problems with type
1278 /// inference. As such, `collect()` is one of the few times you'll see
1279 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1280 /// helps the inference algorithm understand specifically which collection
1281 /// you're trying to collect into.
1288 /// let a = [1, 2, 3];
1290 /// let doubled: Vec<i32> = a.iter()
1291 /// .map(|&x| x * 2)
1294 /// assert_eq!(vec![2, 4, 6], doubled);
1297 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1298 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1300 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1303 /// use std::collections::VecDeque;
1305 /// let a = [1, 2, 3];
1307 /// let doubled: VecDeque<i32> = a.iter()
1308 /// .map(|&x| x * 2)
1311 /// assert_eq!(2, doubled[0]);
1312 /// assert_eq!(4, doubled[1]);
1313 /// assert_eq!(6, doubled[2]);
1316 /// Using the 'turbofish' instead of annotating `doubled`:
1319 /// let a = [1, 2, 3];
1321 /// let doubled = a.iter()
1322 /// .map(|&x| x * 2)
1323 /// .collect::<Vec<i32>>();
1325 /// assert_eq!(vec![2, 4, 6], doubled);
1328 /// Because `collect()` only cares about what you're collecting into, you can
1329 /// still use a partial type hint, `_`, with the turbofish:
1332 /// let a = [1, 2, 3];
1334 /// let doubled = a.iter()
1335 /// .map(|&x| x * 2)
1336 /// .collect::<Vec<_>>();
1338 /// assert_eq!(vec![2, 4, 6], doubled);
1341 /// Using `collect()` to make a [`String`]:
1344 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1346 /// let hello: String = chars.iter()
1347 /// .map(|&x| x as u8)
1348 /// .map(|x| (x + 1) as char)
1351 /// assert_eq!("hello", hello);
1354 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1355 /// see if any of them failed:
1358 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1360 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1362 /// // gives us the first error
1363 /// assert_eq!(Err("nope"), result);
1365 /// let results = [Ok(1), Ok(3)];
1367 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1369 /// // gives us the list of answers
1370 /// assert_eq!(Ok(vec![1, 3]), result);
1373 /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1374 /// [`String`]: ../../std/string/struct.String.html
1375 /// [`char`]: ../../std/primitive.char.html
1376 /// [`Result`]: ../../std/result/enum.Result.html
1378 #[stable(feature = "rust1", since = "1.0.0")]
1379 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1380 FromIterator::from_iter(self)
1383 /// Consumes an iterator, creating two collections from it.
1385 /// The predicate passed to `partition()` can return `true`, or `false`.
1386 /// `partition()` returns a pair, all of the elements for which it returned
1387 /// `true`, and all of the elements for which it returned `false`.
1394 /// let a = [1, 2, 3];
1396 /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1397 /// .partition(|&n| n % 2 == 0);
1399 /// assert_eq!(even, vec![2]);
1400 /// assert_eq!(odd, vec![1, 3]);
1402 #[stable(feature = "rust1", since = "1.0.0")]
1403 fn partition<B, F>(self, mut f: F) -> (B, B) where
1405 B: Default + Extend<Self::Item>,
1406 F: FnMut(&Self::Item) -> bool
1408 let mut left: B = Default::default();
1409 let mut right: B = Default::default();
1413 left.extend(Some(x))
1415 right.extend(Some(x))
1422 /// An iterator method that applies a function as long as it returns
1423 /// successfully, producing a single, final value.
1425 /// `try_fold()` takes two arguments: an initial value, and a closure with
1426 /// two arguments: an 'accumulator', and an element. The closure either
1427 /// returns successfully, with the value that the accumulator should have
1428 /// for the next iteration, or it returns failure, with an error value that
1429 /// is propagated back to the caller immediately (short-circuiting).
1431 /// The initial value is the value the accumulator will have on the first
1432 /// call. If applying the closure succeeded against every element of the
1433 /// iterator, `try_fold()` returns the final accumulator as success.
1435 /// Folding is useful whenever you have a collection of something, and want
1436 /// to produce a single value from it.
1438 /// # Note to Implementors
1440 /// Most of the other (forward) methods have default implementations in
1441 /// terms of this one, so try to implement this explicitly if it can
1442 /// do something better than the default `for` loop implementation.
1444 /// In particular, try to have this call `try_fold()` on the internal parts
1445 /// from which this iterator is composed. If multiple calls are needed,
1446 /// the `?` operator may be convenient for chaining the accumulator value
1447 /// along, but beware any invariants that need to be upheld before those
1448 /// early returns. This is a `&mut self` method, so iteration needs to be
1449 /// resumable after hitting an error here.
1456 /// #![feature(iterator_try_fold)]
1457 /// let a = [1, 2, 3];
1459 /// // the checked sum of all of the elements of the array
1460 /// let sum = a.iter()
1461 /// .try_fold(0i8, |acc, &x| acc.checked_add(x));
1463 /// assert_eq!(sum, Some(6));
1466 /// Short-circuiting:
1469 /// #![feature(iterator_try_fold)]
1470 /// let a = [10, 20, 30, 100, 40, 50];
1471 /// let mut it = a.iter();
1473 /// // This sum overflows when adding the 100 element
1474 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1475 /// assert_eq!(sum, None);
1477 /// // Because it short-circuited, the remaining elements are still
1478 /// // available through the iterator.
1479 /// assert_eq!(it.len(), 2);
1480 /// assert_eq!(it.next(), Some(&40));
1483 #[unstable(feature = "iterator_try_fold", issue = "45594")]
1484 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
1485 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
1487 let mut accum = init;
1488 while let Some(x) = self.next() {
1489 accum = f(accum, x)?;
1494 /// An iterator method that applies a fallible function to each item in the
1495 /// iterator, stopping at the first error and returning that error.
1497 /// This can also be thought of as the fallible form of [`for_each()`]
1498 /// or as the stateless version of [`try_fold()`].
1500 /// [`for_each()`]: #method.for_each
1501 /// [`try_fold()`]: #method.try_fold
1506 /// #![feature(iterator_try_fold)]
1507 /// use std::fs::rename;
1508 /// use std::io::{stdout, Write};
1509 /// use std::path::Path;
1511 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
1513 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
1514 /// assert!(res.is_ok());
1516 /// let mut it = data.iter().cloned();
1517 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
1518 /// assert!(res.is_err());
1519 /// // It short-circuited, so the remaining items are still in the iterator:
1520 /// assert_eq!(it.next(), Some("stale_bread.json"));
1523 #[unstable(feature = "iterator_try_fold", issue = "45594")]
1524 fn try_for_each<F, R>(&mut self, mut f: F) -> R where
1525 Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Ok=()>
1527 self.try_fold((), move |(), x| f(x))
1530 /// An iterator method that applies a function, producing a single, final value.
1532 /// `fold()` takes two arguments: an initial value, and a closure with two
1533 /// arguments: an 'accumulator', and an element. The closure returns the value that
1534 /// the accumulator should have for the next iteration.
1536 /// The initial value is the value the accumulator will have on the first
1539 /// After applying this closure to every element of the iterator, `fold()`
1540 /// returns the accumulator.
1542 /// This operation is sometimes called 'reduce' or 'inject'.
1544 /// Folding is useful whenever you have a collection of something, and want
1545 /// to produce a single value from it.
1547 /// Note: `fold()`, and similar methods that traverse the entire iterator,
1548 /// may not terminate for infinite iterators, even on traits for which a
1549 /// result is determinable in finite time.
1556 /// let a = [1, 2, 3];
1558 /// // the sum of all of the elements of the array
1559 /// let sum = a.iter()
1560 /// .fold(0, |acc, &x| acc + x);
1562 /// assert_eq!(sum, 6);
1565 /// Let's walk through each step of the iteration here:
1567 /// | element | acc | x | result |
1568 /// |---------|-----|---|--------|
1570 /// | 1 | 0 | 1 | 1 |
1571 /// | 2 | 1 | 2 | 3 |
1572 /// | 3 | 3 | 3 | 6 |
1574 /// And so, our final result, `6`.
1576 /// It's common for people who haven't used iterators a lot to
1577 /// use a `for` loop with a list of things to build up a result. Those
1578 /// can be turned into `fold()`s:
1580 /// [`for`]: ../../book/first-edition/loops.html#for
1583 /// let numbers = [1, 2, 3, 4, 5];
1585 /// let mut result = 0;
1588 /// for i in &numbers {
1589 /// result = result + i;
1593 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1595 /// // they're the same
1596 /// assert_eq!(result, result2);
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 fn fold<B, F>(mut self, init: B, mut f: F) -> B where
1601 Self: Sized, F: FnMut(B, Self::Item) -> B,
1603 self.try_fold(init, move |acc, x| AlwaysOk(f(acc, x))).0
1606 /// Tests if every element of the iterator matches a predicate.
1608 /// `all()` takes a closure that returns `true` or `false`. It applies
1609 /// this closure to each element of the iterator, and if they all return
1610 /// `true`, then so does `all()`. If any of them return `false`, it
1611 /// returns `false`.
1613 /// `all()` is short-circuiting; in other words, it will stop processing
1614 /// as soon as it finds a `false`, given that no matter what else happens,
1615 /// the result will also be `false`.
1617 /// An empty iterator returns `true`.
1624 /// let a = [1, 2, 3];
1626 /// assert!(a.iter().all(|&x| x > 0));
1628 /// assert!(!a.iter().all(|&x| x > 2));
1631 /// Stopping at the first `false`:
1634 /// let a = [1, 2, 3];
1636 /// let mut iter = a.iter();
1638 /// assert!(!iter.all(|&x| x != 2));
1640 /// // we can still use `iter`, as there are more elements.
1641 /// assert_eq!(iter.next(), Some(&3));
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 fn all<F>(&mut self, mut f: F) -> bool where
1646 Self: Sized, F: FnMut(Self::Item) -> bool
1648 self.try_for_each(move |x| {
1649 if f(x) { LoopState::Continue(()) }
1650 else { LoopState::Break(()) }
1651 }) == LoopState::Continue(())
1654 /// Tests if any element of the iterator matches a predicate.
1656 /// `any()` takes a closure that returns `true` or `false`. It applies
1657 /// this closure to each element of the iterator, and if any of them return
1658 /// `true`, then so does `any()`. If they all return `false`, it
1659 /// returns `false`.
1661 /// `any()` is short-circuiting; in other words, it will stop processing
1662 /// as soon as it finds a `true`, given that no matter what else happens,
1663 /// the result will also be `true`.
1665 /// An empty iterator returns `false`.
1672 /// let a = [1, 2, 3];
1674 /// assert!(a.iter().any(|&x| x > 0));
1676 /// assert!(!a.iter().any(|&x| x > 5));
1679 /// Stopping at the first `true`:
1682 /// let a = [1, 2, 3];
1684 /// let mut iter = a.iter();
1686 /// assert!(iter.any(|&x| x != 2));
1688 /// // we can still use `iter`, as there are more elements.
1689 /// assert_eq!(iter.next(), Some(&2));
1692 #[stable(feature = "rust1", since = "1.0.0")]
1693 fn any<F>(&mut self, mut f: F) -> bool where
1695 F: FnMut(Self::Item) -> bool
1697 self.try_for_each(move |x| {
1698 if f(x) { LoopState::Break(()) }
1699 else { LoopState::Continue(()) }
1700 }) == LoopState::Break(())
1703 /// Searches for an element of an iterator that satisfies a predicate.
1705 /// `find()` takes a closure that returns `true` or `false`. It applies
1706 /// this closure to each element of the iterator, and if any of them return
1707 /// `true`, then `find()` returns [`Some(element)`]. If they all return
1708 /// `false`, it returns [`None`].
1710 /// `find()` is short-circuiting; in other words, it will stop processing
1711 /// as soon as the closure returns `true`.
1713 /// Because `find()` takes a reference, and many iterators iterate over
1714 /// references, this leads to a possibly confusing situation where the
1715 /// argument is a double reference. You can see this effect in the
1716 /// examples below, with `&&x`.
1718 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
1719 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1726 /// let a = [1, 2, 3];
1728 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1730 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1733 /// Stopping at the first `true`:
1736 /// let a = [1, 2, 3];
1738 /// let mut iter = a.iter();
1740 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1742 /// // we can still use `iter`, as there are more elements.
1743 /// assert_eq!(iter.next(), Some(&3));
1746 #[stable(feature = "rust1", since = "1.0.0")]
1747 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1749 P: FnMut(&Self::Item) -> bool,
1751 self.try_for_each(move |x| {
1752 if predicate(&x) { LoopState::Break(x) }
1753 else { LoopState::Continue(()) }
1757 /// Searches for an element in an iterator, returning its index.
1759 /// `position()` takes a closure that returns `true` or `false`. It applies
1760 /// this closure to each element of the iterator, and if one of them
1761 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
1762 /// them return `false`, it returns [`None`].
1764 /// `position()` is short-circuiting; in other words, it will stop
1765 /// processing as soon as it finds a `true`.
1767 /// # Overflow Behavior
1769 /// The method does no guarding against overflows, so if there are more
1770 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
1771 /// result or panics. If debug assertions are enabled, a panic is
1776 /// This function might panic if the iterator has more than `usize::MAX`
1777 /// non-matching elements.
1779 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1780 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1781 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
1788 /// let a = [1, 2, 3];
1790 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1792 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1795 /// Stopping at the first `true`:
1798 /// let a = [1, 2, 3, 4];
1800 /// let mut iter = a.iter();
1802 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
1804 /// // we can still use `iter`, as there are more elements.
1805 /// assert_eq!(iter.next(), Some(&3));
1807 /// // The returned index depends on iterator state
1808 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
1812 #[rustc_inherit_overflow_checks]
1813 #[stable(feature = "rust1", since = "1.0.0")]
1814 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1816 P: FnMut(Self::Item) -> bool,
1818 // The addition might panic on overflow
1819 self.try_fold(0, move |i, x| {
1820 if predicate(x) { LoopState::Break(i) }
1821 else { LoopState::Continue(i + 1) }
1825 /// Searches for an element in an iterator from the right, returning its
1828 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1829 /// this closure to each element of the iterator, starting from the end,
1830 /// and if one of them returns `true`, then `rposition()` returns
1831 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
1833 /// `rposition()` is short-circuiting; in other words, it will stop
1834 /// processing as soon as it finds a `true`.
1836 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1837 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1844 /// let a = [1, 2, 3];
1846 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1848 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1851 /// Stopping at the first `true`:
1854 /// let a = [1, 2, 3];
1856 /// let mut iter = a.iter();
1858 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1860 /// // we can still use `iter`, as there are more elements.
1861 /// assert_eq!(iter.next(), Some(&1));
1864 #[stable(feature = "rust1", since = "1.0.0")]
1865 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1866 P: FnMut(Self::Item) -> bool,
1867 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1869 // No need for an overflow check here, because `ExactSizeIterator`
1870 // implies that the number of elements fits into a `usize`.
1872 self.try_rfold(n, move |i, x| {
1874 if predicate(x) { LoopState::Break(i) }
1875 else { LoopState::Continue(i) }
1879 /// Returns the maximum element of an iterator.
1881 /// If several elements are equally maximum, the last element is
1882 /// returned. If the iterator is empty, [`None`] is returned.
1884 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1891 /// let a = [1, 2, 3];
1892 /// let b: Vec<u32> = Vec::new();
1894 /// assert_eq!(a.iter().max(), Some(&3));
1895 /// assert_eq!(b.iter().max(), None);
1898 #[stable(feature = "rust1", since = "1.0.0")]
1899 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1903 // switch to y even if it is only equal, to preserve
1905 |_, x, _, y| *x <= *y)
1909 /// Returns the minimum element of an iterator.
1911 /// If several elements are equally minimum, the first element is
1912 /// returned. If the iterator is empty, [`None`] is returned.
1914 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1921 /// let a = [1, 2, 3];
1922 /// let b: Vec<u32> = Vec::new();
1924 /// assert_eq!(a.iter().min(), Some(&1));
1925 /// assert_eq!(b.iter().min(), None);
1928 #[stable(feature = "rust1", since = "1.0.0")]
1929 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1933 // only switch to y if it is strictly smaller, to
1934 // preserve stability.
1935 |_, x, _, y| *x > *y)
1939 /// Returns the element that gives the maximum value from the
1940 /// specified function.
1942 /// If several elements are equally maximum, the last element is
1943 /// returned. If the iterator is empty, [`None`] is returned.
1945 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1950 /// let a = [-3_i32, 0, 1, 5, -10];
1951 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1954 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1955 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1956 where Self: Sized, F: FnMut(&Self::Item) -> B,
1960 // switch to y even if it is only equal, to preserve
1962 |x_p, _, y_p, _| x_p <= y_p)
1966 /// Returns the element that gives the maximum value with respect to the
1967 /// specified comparison function.
1969 /// If several elements are equally maximum, the last element is
1970 /// returned. If the iterator is empty, [`None`] is returned.
1972 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1977 /// let a = [-3_i32, 0, 1, 5, -10];
1978 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
1981 #[stable(feature = "iter_max_by", since = "1.15.0")]
1982 fn max_by<F>(self, mut compare: F) -> Option<Self::Item>
1983 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1987 // switch to y even if it is only equal, to preserve
1989 |_, x, _, y| Ordering::Greater != compare(x, y))
1993 /// Returns the element that gives the minimum value from the
1994 /// specified function.
1996 /// If several elements are equally minimum, the first element is
1997 /// returned. If the iterator is empty, [`None`] is returned.
1999 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2004 /// let a = [-3_i32, 0, 1, 5, -10];
2005 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2007 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2008 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2009 where Self: Sized, F: FnMut(&Self::Item) -> B,
2013 // only switch to y if it is strictly smaller, to
2014 // preserve stability.
2015 |x_p, _, y_p, _| x_p > y_p)
2019 /// Returns the element that gives the minimum value with respect to the
2020 /// specified comparison function.
2022 /// If several elements are equally minimum, the first element is
2023 /// returned. If the iterator is empty, [`None`] is returned.
2025 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2030 /// let a = [-3_i32, 0, 1, 5, -10];
2031 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2034 #[stable(feature = "iter_min_by", since = "1.15.0")]
2035 fn min_by<F>(self, mut compare: F) -> Option<Self::Item>
2036 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2040 // switch to y even if it is strictly smaller, to
2041 // preserve stability.
2042 |_, x, _, y| Ordering::Greater == compare(x, y))
2047 /// Reverses an iterator's direction.
2049 /// Usually, iterators iterate from left to right. After using `rev()`,
2050 /// an iterator will instead iterate from right to left.
2052 /// This is only possible if the iterator has an end, so `rev()` only
2053 /// works on [`DoubleEndedIterator`]s.
2055 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
2060 /// let a = [1, 2, 3];
2062 /// let mut iter = a.iter().rev();
2064 /// assert_eq!(iter.next(), Some(&3));
2065 /// assert_eq!(iter.next(), Some(&2));
2066 /// assert_eq!(iter.next(), Some(&1));
2068 /// assert_eq!(iter.next(), None);
2071 #[stable(feature = "rust1", since = "1.0.0")]
2072 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
2076 /// Converts an iterator of pairs into a pair of containers.
2078 /// `unzip()` consumes an entire iterator of pairs, producing two
2079 /// collections: one from the left elements of the pairs, and one
2080 /// from the right elements.
2082 /// This function is, in some sense, the opposite of [`zip`].
2084 /// [`zip`]: #method.zip
2091 /// let a = [(1, 2), (3, 4)];
2093 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2095 /// assert_eq!(left, [1, 3]);
2096 /// assert_eq!(right, [2, 4]);
2098 #[stable(feature = "rust1", since = "1.0.0")]
2099 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
2100 FromA: Default + Extend<A>,
2101 FromB: Default + Extend<B>,
2102 Self: Sized + Iterator<Item=(A, B)>,
2104 let mut ts: FromA = Default::default();
2105 let mut us: FromB = Default::default();
2107 self.for_each(|(t, u)| {
2115 /// Creates an iterator which [`clone`]s all of its elements.
2117 /// This is useful when you have an iterator over `&T`, but you need an
2118 /// iterator over `T`.
2120 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
2127 /// let a = [1, 2, 3];
2129 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2131 /// // cloned is the same as .map(|&x| x), for integers
2132 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2134 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2135 /// assert_eq!(v_map, vec![1, 2, 3]);
2137 #[stable(feature = "rust1", since = "1.0.0")]
2138 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2139 where Self: Sized + Iterator<Item=&'a T>, T: Clone
2144 /// Repeats an iterator endlessly.
2146 /// Instead of stopping at [`None`], the iterator will instead start again,
2147 /// from the beginning. After iterating again, it will start at the
2148 /// beginning again. And again. And again. Forever.
2150 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2157 /// let a = [1, 2, 3];
2159 /// let mut it = a.iter().cycle();
2161 /// assert_eq!(it.next(), Some(&1));
2162 /// assert_eq!(it.next(), Some(&2));
2163 /// assert_eq!(it.next(), Some(&3));
2164 /// assert_eq!(it.next(), Some(&1));
2165 /// assert_eq!(it.next(), Some(&2));
2166 /// assert_eq!(it.next(), Some(&3));
2167 /// assert_eq!(it.next(), Some(&1));
2169 #[stable(feature = "rust1", since = "1.0.0")]
2171 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
2172 Cycle{orig: self.clone(), iter: self}
2175 /// Sums the elements of an iterator.
2177 /// Takes each element, adds them together, and returns the result.
2179 /// An empty iterator returns the zero value of the type.
2183 /// When calling `sum()` and a primitive integer type is being returned, this
2184 /// method will panic if the computation overflows and debug assertions are
2192 /// let a = [1, 2, 3];
2193 /// let sum: i32 = a.iter().sum();
2195 /// assert_eq!(sum, 6);
2197 #[stable(feature = "iter_arith", since = "1.11.0")]
2198 fn sum<S>(self) -> S
2205 /// Iterates over the entire iterator, multiplying all the elements
2207 /// An empty iterator returns the one value of the type.
2211 /// When calling `product()` and a primitive integer type is being returned,
2212 /// method will panic if the computation overflows and debug assertions are
2218 /// fn factorial(n: u32) -> u32 {
2219 /// (1..).take_while(|&i| i <= n).product()
2221 /// assert_eq!(factorial(0), 1);
2222 /// assert_eq!(factorial(1), 1);
2223 /// assert_eq!(factorial(5), 120);
2225 #[stable(feature = "iter_arith", since = "1.11.0")]
2226 fn product<P>(self) -> P
2228 P: Product<Self::Item>,
2230 Product::product(self)
2233 /// Lexicographically compares the elements of this `Iterator` with those
2235 #[stable(feature = "iter_order", since = "1.5.0")]
2236 fn cmp<I>(mut self, other: I) -> Ordering where
2237 I: IntoIterator<Item = Self::Item>,
2241 let mut other = other.into_iter();
2244 let x = match self.next() {
2245 None => if other.next().is_none() {
2246 return Ordering::Equal
2248 return Ordering::Less
2253 let y = match other.next() {
2254 None => return Ordering::Greater,
2259 Ordering::Equal => (),
2260 non_eq => return non_eq,
2265 /// Lexicographically compares the elements of this `Iterator` with those
2267 #[stable(feature = "iter_order", since = "1.5.0")]
2268 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2270 Self::Item: PartialOrd<I::Item>,
2273 let mut other = other.into_iter();
2276 let x = match self.next() {
2277 None => if other.next().is_none() {
2278 return Some(Ordering::Equal)
2280 return Some(Ordering::Less)
2285 let y = match other.next() {
2286 None => return Some(Ordering::Greater),
2290 match x.partial_cmp(&y) {
2291 Some(Ordering::Equal) => (),
2292 non_eq => return non_eq,
2297 /// Determines if the elements of this `Iterator` are equal to those of
2299 #[stable(feature = "iter_order", since = "1.5.0")]
2300 fn eq<I>(mut self, other: I) -> bool where
2302 Self::Item: PartialEq<I::Item>,
2305 let mut other = other.into_iter();
2308 let x = match self.next() {
2309 None => return other.next().is_none(),
2313 let y = match other.next() {
2314 None => return false,
2318 if x != y { return false }
2322 /// Determines if the elements of this `Iterator` are unequal to those of
2324 #[stable(feature = "iter_order", since = "1.5.0")]
2325 fn ne<I>(mut self, other: I) -> bool where
2327 Self::Item: PartialEq<I::Item>,
2330 let mut other = other.into_iter();
2333 let x = match self.next() {
2334 None => return other.next().is_some(),
2338 let y = match other.next() {
2339 None => return true,
2343 if x != y { return true }
2347 /// Determines if the elements of this `Iterator` are lexicographically
2348 /// less than those of another.
2349 #[stable(feature = "iter_order", since = "1.5.0")]
2350 fn lt<I>(mut self, other: I) -> bool where
2352 Self::Item: PartialOrd<I::Item>,
2355 let mut other = other.into_iter();
2358 let x = match self.next() {
2359 None => return other.next().is_some(),
2363 let y = match other.next() {
2364 None => return false,
2368 match x.partial_cmp(&y) {
2369 Some(Ordering::Less) => return true,
2370 Some(Ordering::Equal) => (),
2371 Some(Ordering::Greater) => return false,
2372 None => return false,
2377 /// Determines if the elements of this `Iterator` are lexicographically
2378 /// less or equal to those of another.
2379 #[stable(feature = "iter_order", since = "1.5.0")]
2380 fn le<I>(mut self, other: I) -> bool where
2382 Self::Item: PartialOrd<I::Item>,
2385 let mut other = other.into_iter();
2388 let x = match self.next() {
2389 None => { other.next(); return true; },
2393 let y = match other.next() {
2394 None => return false,
2398 match x.partial_cmp(&y) {
2399 Some(Ordering::Less) => return true,
2400 Some(Ordering::Equal) => (),
2401 Some(Ordering::Greater) => return false,
2402 None => return false,
2407 /// Determines if the elements of this `Iterator` are lexicographically
2408 /// greater than those of another.
2409 #[stable(feature = "iter_order", since = "1.5.0")]
2410 fn gt<I>(mut self, other: I) -> bool where
2412 Self::Item: PartialOrd<I::Item>,
2415 let mut other = other.into_iter();
2418 let x = match self.next() {
2419 None => { other.next(); return false; },
2423 let y = match other.next() {
2424 None => return true,
2428 match x.partial_cmp(&y) {
2429 Some(Ordering::Less) => return false,
2430 Some(Ordering::Equal) => (),
2431 Some(Ordering::Greater) => return true,
2432 None => return false,
2437 /// Determines if the elements of this `Iterator` are lexicographically
2438 /// greater than or equal to those of another.
2439 #[stable(feature = "iter_order", since = "1.5.0")]
2440 fn ge<I>(mut self, other: I) -> bool where
2442 Self::Item: PartialOrd<I::Item>,
2445 let mut other = other.into_iter();
2448 let x = match self.next() {
2449 None => return other.next().is_none(),
2453 let y = match other.next() {
2454 None => return true,
2458 match x.partial_cmp(&y) {
2459 Some(Ordering::Less) => return false,
2460 Some(Ordering::Equal) => (),
2461 Some(Ordering::Greater) => return true,
2462 None => return false,
2468 /// Select an element from an iterator based on the given "projection"
2469 /// and "comparison" function.
2471 /// This is an idiosyncratic helper to try to factor out the
2472 /// commonalities of {max,min}{,_by}. In particular, this avoids
2473 /// having to implement optimizations several times.
2475 fn select_fold1<I, B, FProj, FCmp>(mut it: I,
2477 mut f_cmp: FCmp) -> Option<(B, I::Item)>
2479 FProj: FnMut(&I::Item) -> B,
2480 FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2482 // start with the first element as our selection. This avoids
2483 // having to use `Option`s inside the loop, translating to a
2484 // sizeable performance gain (6x in one case).
2485 it.next().map(|first| {
2486 let first_p = f_proj(&first);
2488 it.fold((first_p, first), |(sel_p, sel), x| {
2489 let x_p = f_proj(&x);
2490 if f_cmp(&sel_p, &sel, &x_p, &x) {
2499 #[stable(feature = "rust1", since = "1.0.0")]
2500 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2501 type Item = I::Item;
2502 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2503 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2504 fn nth(&mut self, n: usize) -> Option<Self::Item> {