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.
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(_: &dyn 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 1: The first element of the iterator will always be returned,
275 /// regardless of the step given.
277 /// Note 2: The time at which ignored elements are pulled is not fixed.
278 /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
279 /// but is also free to behave like the sequence
280 /// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
281 /// Which way is used may change for some iterators for performance reasons.
282 /// The second way will advance the iterator earlier and may consume more items.
284 /// `advance_n_and_return_first` is the equivalent of:
286 /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
290 /// let next = iter.next();
291 /// if total_step > 1 {
292 /// iter.nth(total_step-2);
300 /// The method will panic if the given step is `0`.
307 /// let a = [0, 1, 2, 3, 4, 5];
308 /// let mut iter = a.into_iter().step_by(2);
310 /// assert_eq!(iter.next(), Some(&0));
311 /// assert_eq!(iter.next(), Some(&2));
312 /// assert_eq!(iter.next(), Some(&4));
313 /// assert_eq!(iter.next(), None);
316 #[stable(feature = "iterator_step_by", since = "1.28.0")]
317 fn step_by(self, step: usize) -> StepBy<Self> where Self: Sized {
319 StepBy{iter: self, step: step - 1, first_take: true}
322 /// Takes two iterators and creates a new iterator over both in sequence.
324 /// `chain()` will return a new iterator which will first iterate over
325 /// values from the first iterator and then over values from the second
328 /// In other words, it links two iterators together, in a chain. 🔗
335 /// let a1 = [1, 2, 3];
336 /// let a2 = [4, 5, 6];
338 /// let mut iter = a1.iter().chain(a2.iter());
340 /// assert_eq!(iter.next(), Some(&1));
341 /// assert_eq!(iter.next(), Some(&2));
342 /// assert_eq!(iter.next(), Some(&3));
343 /// assert_eq!(iter.next(), Some(&4));
344 /// assert_eq!(iter.next(), Some(&5));
345 /// assert_eq!(iter.next(), Some(&6));
346 /// assert_eq!(iter.next(), None);
349 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
350 /// anything that can be converted into an [`Iterator`], not just an
351 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
352 /// [`IntoIterator`], and so can be passed to `chain()` directly:
354 /// [`IntoIterator`]: trait.IntoIterator.html
355 /// [`Iterator`]: trait.Iterator.html
358 /// let s1 = &[1, 2, 3];
359 /// let s2 = &[4, 5, 6];
361 /// let mut iter = s1.iter().chain(s2);
363 /// assert_eq!(iter.next(), Some(&1));
364 /// assert_eq!(iter.next(), Some(&2));
365 /// assert_eq!(iter.next(), Some(&3));
366 /// assert_eq!(iter.next(), Some(&4));
367 /// assert_eq!(iter.next(), Some(&5));
368 /// assert_eq!(iter.next(), Some(&6));
369 /// assert_eq!(iter.next(), None);
372 #[stable(feature = "rust1", since = "1.0.0")]
373 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
374 Self: Sized, U: IntoIterator<Item=Self::Item>,
376 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
379 /// 'Zips up' two iterators into a single iterator of pairs.
381 /// `zip()` returns a new iterator that will iterate over two other
382 /// iterators, returning a tuple where the first element comes from the
383 /// first iterator, and the second element comes from the second iterator.
385 /// In other words, it zips two iterators together, into a single one.
387 /// If either iterator returns [`None`], [`next`] from the zipped iterator
388 /// will return [`None`]. If the first iterator returns [`None`], `zip` will
389 /// short-circuit and `next` will not be called on the second iterator.
396 /// let a1 = [1, 2, 3];
397 /// let a2 = [4, 5, 6];
399 /// let mut iter = a1.iter().zip(a2.iter());
401 /// assert_eq!(iter.next(), Some((&1, &4)));
402 /// assert_eq!(iter.next(), Some((&2, &5)));
403 /// assert_eq!(iter.next(), Some((&3, &6)));
404 /// assert_eq!(iter.next(), None);
407 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
408 /// anything that can be converted into an [`Iterator`], not just an
409 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
410 /// [`IntoIterator`], and so can be passed to `zip()` directly:
412 /// [`IntoIterator`]: trait.IntoIterator.html
413 /// [`Iterator`]: trait.Iterator.html
416 /// let s1 = &[1, 2, 3];
417 /// let s2 = &[4, 5, 6];
419 /// let mut iter = s1.iter().zip(s2);
421 /// assert_eq!(iter.next(), Some((&1, &4)));
422 /// assert_eq!(iter.next(), Some((&2, &5)));
423 /// assert_eq!(iter.next(), Some((&3, &6)));
424 /// assert_eq!(iter.next(), None);
427 /// `zip()` is often used to zip an infinite iterator to a finite one.
428 /// This works because the finite iterator will eventually return [`None`],
429 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
432 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
434 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
436 /// assert_eq!((0, 'f'), enumerate[0]);
437 /// assert_eq!((0, 'f'), zipper[0]);
439 /// assert_eq!((1, 'o'), enumerate[1]);
440 /// assert_eq!((1, 'o'), zipper[1]);
442 /// assert_eq!((2, 'o'), enumerate[2]);
443 /// assert_eq!((2, 'o'), zipper[2]);
446 /// [`enumerate`]: trait.Iterator.html#method.enumerate
447 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
448 /// [`None`]: ../../std/option/enum.Option.html#variant.None
450 #[stable(feature = "rust1", since = "1.0.0")]
451 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
452 Self: Sized, U: IntoIterator
454 Zip::new(self, other.into_iter())
457 /// Takes a closure and creates an iterator which calls that closure on each
460 /// `map()` transforms one iterator into another, by means of its argument:
461 /// something that implements `FnMut`. It produces a new iterator which
462 /// calls this closure on each element of the original iterator.
464 /// If you are good at thinking in types, you can think of `map()` like this:
465 /// If you have an iterator that gives you elements of some type `A`, and
466 /// you want an iterator of some other type `B`, you can use `map()`,
467 /// passing a closure that takes an `A` and returns a `B`.
469 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
470 /// lazy, it is best used when you're already working with other iterators.
471 /// If you're doing some sort of looping for a side effect, it's considered
472 /// more idiomatic to use [`for`] than `map()`.
474 /// [`for`]: ../../book/first-edition/loops.html#for
481 /// let a = [1, 2, 3];
483 /// let mut iter = a.into_iter().map(|x| 2 * x);
485 /// assert_eq!(iter.next(), Some(2));
486 /// assert_eq!(iter.next(), Some(4));
487 /// assert_eq!(iter.next(), Some(6));
488 /// assert_eq!(iter.next(), None);
491 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
494 /// # #![allow(unused_must_use)]
495 /// // don't do this:
496 /// (0..5).map(|x| println!("{}", x));
498 /// // it won't even execute, as it is lazy. Rust will warn you about this.
500 /// // Instead, use for:
502 /// println!("{}", x);
506 #[stable(feature = "rust1", since = "1.0.0")]
507 fn map<B, F>(self, f: F) -> Map<Self, F> where
508 Self: Sized, F: FnMut(Self::Item) -> B,
510 Map { iter: self, f }
513 /// Calls a closure on each element of an iterator.
515 /// This is equivalent to using a [`for`] loop on the iterator, although
516 /// `break` and `continue` are not possible from a closure. It's generally
517 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
518 /// when processing items at the end of longer iterator chains. In some
519 /// cases `for_each` may also be faster than a loop, because it will use
520 /// internal iteration on adaptors like `Chain`.
522 /// [`for`]: ../../book/first-edition/loops.html#for
529 /// use std::sync::mpsc::channel;
531 /// let (tx, rx) = channel();
532 /// (0..5).map(|x| x * 2 + 1)
533 /// .for_each(move |x| tx.send(x).unwrap());
535 /// let v: Vec<_> = rx.iter().collect();
536 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
539 /// For such a small example, a `for` loop may be cleaner, but `for_each`
540 /// might be preferable to keep a functional style with longer iterators:
543 /// (0..5).flat_map(|x| x * 100 .. x * 110)
545 /// .filter(|&(i, x)| (i + x) % 3 == 0)
546 /// .for_each(|(i, x)| println!("{}:{}", i, x));
549 #[stable(feature = "iterator_for_each", since = "1.21.0")]
550 fn for_each<F>(self, mut f: F) where
551 Self: Sized, F: FnMut(Self::Item),
553 self.fold((), move |(), item| f(item));
556 /// Creates an iterator which uses a closure to determine if an element
557 /// should be yielded.
559 /// The closure must return `true` or `false`. `filter()` creates an
560 /// iterator which calls this closure on each element. If the closure
561 /// returns `true`, then the element is returned. If the closure returns
562 /// `false`, it will try again, and call the closure on the next element,
563 /// seeing if it passes the test.
570 /// let a = [0i32, 1, 2];
572 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
574 /// assert_eq!(iter.next(), Some(&1));
575 /// assert_eq!(iter.next(), Some(&2));
576 /// assert_eq!(iter.next(), None);
579 /// Because the closure passed to `filter()` takes a reference, and many
580 /// iterators iterate over references, this leads to a possibly confusing
581 /// situation, where the type of the closure is a double reference:
584 /// let a = [0, 1, 2];
586 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
588 /// assert_eq!(iter.next(), Some(&2));
589 /// assert_eq!(iter.next(), None);
592 /// It's common to instead use destructuring on the argument to strip away
596 /// let a = [0, 1, 2];
598 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
600 /// assert_eq!(iter.next(), Some(&2));
601 /// assert_eq!(iter.next(), None);
607 /// let a = [0, 1, 2];
609 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
611 /// assert_eq!(iter.next(), Some(&2));
612 /// assert_eq!(iter.next(), None);
617 #[stable(feature = "rust1", since = "1.0.0")]
618 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
619 Self: Sized, P: FnMut(&Self::Item) -> bool,
621 Filter {iter: self, predicate }
624 /// Creates an iterator that both filters and maps.
626 /// The closure must return an [`Option<T>`]. `filter_map` creates an
627 /// iterator which calls this closure on each element. If the closure
628 /// returns [`Some(element)`][`Some`], then that element is returned. If the
629 /// closure returns [`None`], it will try again, and call the closure on the
630 /// next element, seeing if it will return [`Some`].
632 /// Why `filter_map` and not just [`filter`] and [`map`]? The key is in this
635 /// [`filter`]: #method.filter
636 /// [`map`]: #method.map
638 /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
640 /// In other words, it removes the [`Option<T>`] layer automatically. If your
641 /// mapping is already returning an [`Option<T>`] and you want to skip over
642 /// [`None`]s, then `filter_map` is much, much nicer to use.
649 /// let a = ["1", "lol", "3", "NaN", "5"];
651 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
653 /// assert_eq!(iter.next(), Some(1));
654 /// assert_eq!(iter.next(), Some(3));
655 /// assert_eq!(iter.next(), Some(5));
656 /// assert_eq!(iter.next(), None);
659 /// Here's the same example, but with [`filter`] and [`map`]:
662 /// let a = ["1", "lol", "3", "NaN", "5"];
663 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
664 /// assert_eq!(iter.next(), Some(1));
665 /// assert_eq!(iter.next(), Some(3));
666 /// assert_eq!(iter.next(), Some(5));
667 /// assert_eq!(iter.next(), None);
670 /// [`Option<T>`]: ../../std/option/enum.Option.html
671 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
672 /// [`None`]: ../../std/option/enum.Option.html#variant.None
674 #[stable(feature = "rust1", since = "1.0.0")]
675 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
676 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
678 FilterMap { iter: self, f }
681 /// Creates an iterator which gives the current iteration count as well as
684 /// The iterator returned yields pairs `(i, val)`, where `i` is the
685 /// current index of iteration and `val` is the value returned by the
688 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
689 /// different sized integer, the [`zip`] function provides similar
692 /// # Overflow Behavior
694 /// The method does no guarding against overflows, so enumerating more than
695 /// [`usize::MAX`] elements either produces the wrong result or panics. If
696 /// debug assertions are enabled, a panic is guaranteed.
700 /// The returned iterator might panic if the to-be-returned index would
701 /// overflow a [`usize`].
703 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
704 /// [`usize`]: ../../std/primitive.usize.html
705 /// [`zip`]: #method.zip
710 /// let a = ['a', 'b', 'c'];
712 /// let mut iter = a.iter().enumerate();
714 /// assert_eq!(iter.next(), Some((0, &'a')));
715 /// assert_eq!(iter.next(), Some((1, &'b')));
716 /// assert_eq!(iter.next(), Some((2, &'c')));
717 /// assert_eq!(iter.next(), None);
720 #[stable(feature = "rust1", since = "1.0.0")]
721 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
722 Enumerate { iter: self, count: 0 }
725 /// Creates an iterator which can use `peek` to look at the next element of
726 /// the iterator without consuming it.
728 /// Adds a [`peek`] method to an iterator. See its documentation for
729 /// more information.
731 /// Note that the underlying iterator is still advanced when [`peek`] is
732 /// called for the first time: In order to retrieve the next element,
733 /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
734 /// anything other than fetching the next value) of the [`next`] method
737 /// [`peek`]: struct.Peekable.html#method.peek
738 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
745 /// let xs = [1, 2, 3];
747 /// let mut iter = xs.iter().peekable();
749 /// // peek() lets us see into the future
750 /// assert_eq!(iter.peek(), Some(&&1));
751 /// assert_eq!(iter.next(), Some(&1));
753 /// assert_eq!(iter.next(), Some(&2));
755 /// // we can peek() multiple times, the iterator won't advance
756 /// assert_eq!(iter.peek(), Some(&&3));
757 /// assert_eq!(iter.peek(), Some(&&3));
759 /// assert_eq!(iter.next(), Some(&3));
761 /// // after the iterator is finished, so is peek()
762 /// assert_eq!(iter.peek(), None);
763 /// assert_eq!(iter.next(), None);
766 #[stable(feature = "rust1", since = "1.0.0")]
767 fn peekable(self) -> Peekable<Self> where Self: Sized {
768 Peekable{iter: self, peeked: None}
771 /// Creates an iterator that [`skip`]s elements based on a predicate.
773 /// [`skip`]: #method.skip
775 /// `skip_while()` takes a closure as an argument. It will call this
776 /// closure on each element of the iterator, and ignore elements
777 /// until it returns `false`.
779 /// After `false` is returned, `skip_while()`'s job is over, and the
780 /// rest of the elements are yielded.
787 /// let a = [-1i32, 0, 1];
789 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
791 /// assert_eq!(iter.next(), Some(&0));
792 /// assert_eq!(iter.next(), Some(&1));
793 /// assert_eq!(iter.next(), None);
796 /// Because the closure passed to `skip_while()` takes a reference, and many
797 /// iterators iterate over references, this leads to a possibly confusing
798 /// situation, where the type of the closure is a double reference:
801 /// let a = [-1, 0, 1];
803 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
805 /// assert_eq!(iter.next(), Some(&0));
806 /// assert_eq!(iter.next(), Some(&1));
807 /// assert_eq!(iter.next(), None);
810 /// Stopping after an initial `false`:
813 /// let a = [-1, 0, 1, -2];
815 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
817 /// assert_eq!(iter.next(), Some(&0));
818 /// assert_eq!(iter.next(), Some(&1));
820 /// // while this would have been false, since we already got a false,
821 /// // skip_while() isn't used any more
822 /// assert_eq!(iter.next(), Some(&-2));
824 /// assert_eq!(iter.next(), None);
827 #[stable(feature = "rust1", since = "1.0.0")]
828 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
829 Self: Sized, P: FnMut(&Self::Item) -> bool,
831 SkipWhile { iter: self, flag: false, predicate }
834 /// Creates an iterator that yields elements based on a predicate.
836 /// `take_while()` takes a closure as an argument. It will call this
837 /// closure on each element of the iterator, and yield elements
838 /// while it returns `true`.
840 /// After `false` is returned, `take_while()`'s job is over, and the
841 /// rest of the elements are ignored.
848 /// let a = [-1i32, 0, 1];
850 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
852 /// assert_eq!(iter.next(), Some(&-1));
853 /// assert_eq!(iter.next(), None);
856 /// Because the closure passed to `take_while()` takes a reference, and many
857 /// iterators iterate over references, this leads to a possibly confusing
858 /// situation, where the type of the closure is a double reference:
861 /// let a = [-1, 0, 1];
863 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
865 /// assert_eq!(iter.next(), Some(&-1));
866 /// assert_eq!(iter.next(), None);
869 /// Stopping after an initial `false`:
872 /// let a = [-1, 0, 1, -2];
874 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
876 /// assert_eq!(iter.next(), Some(&-1));
878 /// // We have more elements that are less than zero, but since we already
879 /// // got a false, take_while() isn't used any more
880 /// assert_eq!(iter.next(), None);
883 /// Because `take_while()` needs to look at the value in order to see if it
884 /// should be included or not, consuming iterators will see that it is
888 /// let a = [1, 2, 3, 4];
889 /// let mut iter = a.into_iter();
891 /// let result: Vec<i32> = iter.by_ref()
892 /// .take_while(|n| **n != 3)
896 /// assert_eq!(result, &[1, 2]);
898 /// let result: Vec<i32> = iter.cloned().collect();
900 /// assert_eq!(result, &[4]);
903 /// The `3` is no longer there, because it was consumed in order to see if
904 /// the iteration should stop, but wasn't placed back into the iterator or
905 /// some similar thing.
907 #[stable(feature = "rust1", since = "1.0.0")]
908 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
909 Self: Sized, P: FnMut(&Self::Item) -> bool,
911 TakeWhile { iter: self, flag: false, predicate }
914 /// Creates an iterator that skips the first `n` elements.
916 /// After they have been consumed, the rest of the elements are yielded.
923 /// let a = [1, 2, 3];
925 /// let mut iter = a.iter().skip(2);
927 /// assert_eq!(iter.next(), Some(&3));
928 /// assert_eq!(iter.next(), None);
931 #[stable(feature = "rust1", since = "1.0.0")]
932 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
933 Skip { iter: self, n }
936 /// Creates an iterator that yields its first `n` elements.
943 /// let a = [1, 2, 3];
945 /// let mut iter = a.iter().take(2);
947 /// assert_eq!(iter.next(), Some(&1));
948 /// assert_eq!(iter.next(), Some(&2));
949 /// assert_eq!(iter.next(), None);
952 /// `take()` is often used with an infinite iterator, to make it finite:
955 /// let mut iter = (0..).take(3);
957 /// assert_eq!(iter.next(), Some(0));
958 /// assert_eq!(iter.next(), Some(1));
959 /// assert_eq!(iter.next(), Some(2));
960 /// assert_eq!(iter.next(), None);
963 #[stable(feature = "rust1", since = "1.0.0")]
964 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
965 Take { iter: self, n }
968 /// An iterator adaptor similar to [`fold`] that holds internal state and
969 /// produces a new iterator.
971 /// [`fold`]: #method.fold
973 /// `scan()` takes two arguments: an initial value which seeds the internal
974 /// state, and a closure with two arguments, the first being a mutable
975 /// reference to the internal state and the second an iterator element.
976 /// The closure can assign to the internal state to share state between
979 /// On iteration, the closure will be applied to each element of the
980 /// iterator and the return value from the closure, an [`Option`], is
981 /// yielded by the iterator.
983 /// [`Option`]: ../../std/option/enum.Option.html
990 /// let a = [1, 2, 3];
992 /// let mut iter = a.iter().scan(1, |state, &x| {
993 /// // each iteration, we'll multiply the state by the element
994 /// *state = *state * x;
996 /// // then, we'll yield the negation of the state
1000 /// assert_eq!(iter.next(), Some(-1));
1001 /// assert_eq!(iter.next(), Some(-2));
1002 /// assert_eq!(iter.next(), Some(-6));
1003 /// assert_eq!(iter.next(), None);
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1008 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
1010 Scan { iter: self, f, state: initial_state }
1013 /// Creates an iterator that works like map, but flattens nested structure.
1015 /// The [`map`] adapter is very useful, but only when the closure
1016 /// argument produces values. If it produces an iterator instead, there's
1017 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1020 /// You can think of `flat_map(f)` as the semantic equivalent
1021 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1023 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1024 /// one item for each element, and `flat_map()`'s closure returns an
1025 /// iterator for each element.
1027 /// [`map`]: #method.map
1028 /// [`flatten`]: #method.flatten
1035 /// let words = ["alpha", "beta", "gamma"];
1037 /// // chars() returns an iterator
1038 /// let merged: String = words.iter()
1039 /// .flat_map(|s| s.chars())
1041 /// assert_eq!(merged, "alphabetagamma");
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1046 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
1048 FlatMap { inner: flatten_compat(self.map(f)) }
1051 /// Creates an iterator that flattens nested structure.
1053 /// This is useful when you have an iterator of iterators or an iterator of
1054 /// things that can be turned into iterators and you want to remove one
1055 /// level of indirection.
1062 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1063 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1064 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1067 /// Mapping and then flattening:
1070 /// let words = ["alpha", "beta", "gamma"];
1072 /// // chars() returns an iterator
1073 /// let merged: String = words.iter()
1074 /// .map(|s| s.chars())
1077 /// assert_eq!(merged, "alphabetagamma");
1080 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1081 /// in this case since it conveys intent more clearly:
1084 /// let words = ["alpha", "beta", "gamma"];
1086 /// // chars() returns an iterator
1087 /// let merged: String = words.iter()
1088 /// .flat_map(|s| s.chars())
1090 /// assert_eq!(merged, "alphabetagamma");
1093 /// Flattening once only removes one level of nesting:
1096 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1098 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1099 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1101 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1102 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1105 /// Here we see that `flatten()` does not perform a "deep" flatten.
1106 /// Instead, only one level of nesting is removed. That is, if you
1107 /// `flatten()` a three-dimensional array the result will be
1108 /// two-dimensional and not one-dimensional. To get a one-dimensional
1109 /// structure, you have to `flatten()` again.
1111 /// [`flat_map()`]: #method.flat_map
1113 #[stable(feature = "iterator_flatten", since = "1.29")]
1114 fn flatten(self) -> Flatten<Self>
1115 where Self: Sized, Self::Item: IntoIterator {
1116 Flatten { inner: flatten_compat(self) }
1119 /// Creates an iterator which ends after the first [`None`].
1121 /// After an iterator returns [`None`], future calls may or may not yield
1122 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1123 /// [`None`] is given, it will always return [`None`] forever.
1125 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1126 /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
1133 /// // an iterator which alternates between Some and None
1134 /// struct Alternate {
1138 /// impl Iterator for Alternate {
1139 /// type Item = i32;
1141 /// fn next(&mut self) -> Option<i32> {
1142 /// let val = self.state;
1143 /// self.state = self.state + 1;
1145 /// // if it's even, Some(i32), else None
1146 /// if val % 2 == 0 {
1154 /// let mut iter = Alternate { state: 0 };
1156 /// // we can see our iterator going back and forth
1157 /// assert_eq!(iter.next(), Some(0));
1158 /// assert_eq!(iter.next(), None);
1159 /// assert_eq!(iter.next(), Some(2));
1160 /// assert_eq!(iter.next(), None);
1162 /// // however, once we fuse it...
1163 /// let mut iter = iter.fuse();
1165 /// assert_eq!(iter.next(), Some(4));
1166 /// assert_eq!(iter.next(), None);
1168 /// // it will always return None after the first time.
1169 /// assert_eq!(iter.next(), None);
1170 /// assert_eq!(iter.next(), None);
1171 /// assert_eq!(iter.next(), None);
1174 #[stable(feature = "rust1", since = "1.0.0")]
1175 fn fuse(self) -> Fuse<Self> where Self: Sized {
1176 Fuse{iter: self, done: false}
1179 /// Do something with each element of an iterator, passing the value on.
1181 /// When using iterators, you'll often chain several of them together.
1182 /// While working on such code, you might want to check out what's
1183 /// happening at various parts in the pipeline. To do that, insert
1184 /// a call to `inspect()`.
1186 /// It's more common for `inspect()` to be used as a debugging tool than to
1187 /// exist in your final code, but applications may find it useful in certain
1188 /// situations when errors need to be logged before being discarded.
1195 /// let a = [1, 4, 2, 3];
1197 /// // this iterator sequence is complex.
1198 /// let sum = a.iter()
1200 /// .filter(|x| x % 2 == 0)
1201 /// .fold(0, |sum, i| sum + i);
1203 /// println!("{}", sum);
1205 /// // let's add some inspect() calls to investigate what's happening
1206 /// let sum = a.iter()
1208 /// .inspect(|x| println!("about to filter: {}", x))
1209 /// .filter(|x| x % 2 == 0)
1210 /// .inspect(|x| println!("made it through filter: {}", x))
1211 /// .fold(0, |sum, i| sum + i);
1213 /// println!("{}", sum);
1216 /// This will print:
1220 /// about to filter: 1
1221 /// about to filter: 4
1222 /// made it through filter: 4
1223 /// about to filter: 2
1224 /// made it through filter: 2
1225 /// about to filter: 3
1229 /// Logging errors before discarding them:
1232 /// let lines = ["1", "2", "a"];
1234 /// let sum: i32 = lines
1236 /// .map(|line| line.parse::<i32>())
1237 /// .inspect(|num| {
1238 /// if let Err(ref e) = *num {
1239 /// println!("Parsing error: {}", e);
1242 /// .filter_map(Result::ok)
1245 /// println!("Sum: {}", sum);
1248 /// This will print:
1251 /// Parsing error: invalid digit found in string
1255 #[stable(feature = "rust1", since = "1.0.0")]
1256 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1257 Self: Sized, F: FnMut(&Self::Item),
1259 Inspect { iter: self, f }
1262 /// Borrows an iterator, rather than consuming it.
1264 /// This is useful to allow applying iterator adaptors while still
1265 /// retaining ownership of the original iterator.
1272 /// let a = [1, 2, 3];
1274 /// let iter = a.into_iter();
1276 /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i );
1278 /// assert_eq!(sum, 6);
1280 /// // if we try to use iter again, it won't work. The following line
1281 /// // gives "error: use of moved value: `iter`
1282 /// // assert_eq!(iter.next(), None);
1284 /// // let's try that again
1285 /// let a = [1, 2, 3];
1287 /// let mut iter = a.into_iter();
1289 /// // instead, we add in a .by_ref()
1290 /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i );
1292 /// assert_eq!(sum, 3);
1294 /// // now this is just fine:
1295 /// assert_eq!(iter.next(), Some(&3));
1296 /// assert_eq!(iter.next(), None);
1298 #[stable(feature = "rust1", since = "1.0.0")]
1299 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1301 /// Transforms an iterator into a collection.
1303 /// `collect()` can take anything iterable, and turn it into a relevant
1304 /// collection. This is one of the more powerful methods in the standard
1305 /// library, used in a variety of contexts.
1307 /// The most basic pattern in which `collect()` is used is to turn one
1308 /// collection into another. You take a collection, call [`iter`] on it,
1309 /// do a bunch of transformations, and then `collect()` at the end.
1311 /// One of the keys to `collect()`'s power is that many things you might
1312 /// not think of as 'collections' actually are. For example, a [`String`]
1313 /// is a collection of [`char`]s. And a collection of
1314 /// [`Result<T, E>`][`Result`] can be thought of as single
1315 /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1317 /// Because `collect()` is so general, it can cause problems with type
1318 /// inference. As such, `collect()` is one of the few times you'll see
1319 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1320 /// helps the inference algorithm understand specifically which collection
1321 /// you're trying to collect into.
1328 /// let a = [1, 2, 3];
1330 /// let doubled: Vec<i32> = a.iter()
1331 /// .map(|&x| x * 2)
1334 /// assert_eq!(vec![2, 4, 6], doubled);
1337 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1338 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1340 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1343 /// use std::collections::VecDeque;
1345 /// let a = [1, 2, 3];
1347 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1349 /// assert_eq!(2, doubled[0]);
1350 /// assert_eq!(4, doubled[1]);
1351 /// assert_eq!(6, doubled[2]);
1354 /// Using the 'turbofish' instead of annotating `doubled`:
1357 /// let a = [1, 2, 3];
1359 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1361 /// assert_eq!(vec![2, 4, 6], doubled);
1364 /// Because `collect()` only cares about what you're collecting into, you can
1365 /// still use a partial type hint, `_`, with the turbofish:
1368 /// let a = [1, 2, 3];
1370 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1372 /// assert_eq!(vec![2, 4, 6], doubled);
1375 /// Using `collect()` to make a [`String`]:
1378 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1380 /// let hello: String = chars.iter()
1381 /// .map(|&x| x as u8)
1382 /// .map(|x| (x + 1) as char)
1385 /// assert_eq!("hello", hello);
1388 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1389 /// see if any of them failed:
1392 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1394 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1396 /// // gives us the first error
1397 /// assert_eq!(Err("nope"), result);
1399 /// let results = [Ok(1), Ok(3)];
1401 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1403 /// // gives us the list of answers
1404 /// assert_eq!(Ok(vec![1, 3]), result);
1407 /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1408 /// [`String`]: ../../std/string/struct.String.html
1409 /// [`char`]: ../../std/primitive.char.html
1410 /// [`Result`]: ../../std/result/enum.Result.html
1412 #[stable(feature = "rust1", since = "1.0.0")]
1413 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1414 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1415 FromIterator::from_iter(self)
1418 /// Consumes an iterator, creating two collections from it.
1420 /// The predicate passed to `partition()` can return `true`, or `false`.
1421 /// `partition()` returns a pair, all of the elements for which it returned
1422 /// `true`, and all of the elements for which it returned `false`.
1429 /// let a = [1, 2, 3];
1431 /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1433 /// .partition(|&n| n % 2 == 0);
1435 /// assert_eq!(even, vec![2]);
1436 /// assert_eq!(odd, vec![1, 3]);
1438 #[stable(feature = "rust1", since = "1.0.0")]
1439 fn partition<B, F>(self, mut f: F) -> (B, B) where
1441 B: Default + Extend<Self::Item>,
1442 F: FnMut(&Self::Item) -> bool
1444 let mut left: B = Default::default();
1445 let mut right: B = Default::default();
1449 left.extend(Some(x))
1451 right.extend(Some(x))
1458 /// An iterator method that applies a function as long as it returns
1459 /// successfully, producing a single, final value.
1461 /// `try_fold()` takes two arguments: an initial value, and a closure with
1462 /// two arguments: an 'accumulator', and an element. The closure either
1463 /// returns successfully, with the value that the accumulator should have
1464 /// for the next iteration, or it returns failure, with an error value that
1465 /// is propagated back to the caller immediately (short-circuiting).
1467 /// The initial value is the value the accumulator will have on the first
1468 /// call. If applying the closure succeeded against every element of the
1469 /// iterator, `try_fold()` returns the final accumulator as success.
1471 /// Folding is useful whenever you have a collection of something, and want
1472 /// to produce a single value from it.
1474 /// # Note to Implementors
1476 /// Most of the other (forward) methods have default implementations in
1477 /// terms of this one, so try to implement this explicitly if it can
1478 /// do something better than the default `for` loop implementation.
1480 /// In particular, try to have this call `try_fold()` on the internal parts
1481 /// from which this iterator is composed. If multiple calls are needed,
1482 /// the `?` operator may be convenient for chaining the accumulator value
1483 /// along, but beware any invariants that need to be upheld before those
1484 /// early returns. This is a `&mut self` method, so iteration needs to be
1485 /// resumable after hitting an error here.
1492 /// let a = [1, 2, 3];
1494 /// // the checked sum of all of the elements of the array
1495 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1497 /// assert_eq!(sum, Some(6));
1500 /// Short-circuiting:
1503 /// let a = [10, 20, 30, 100, 40, 50];
1504 /// let mut it = a.iter();
1506 /// // This sum overflows when adding the 100 element
1507 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1508 /// assert_eq!(sum, None);
1510 /// // Because it short-circuited, the remaining elements are still
1511 /// // available through the iterator.
1512 /// assert_eq!(it.len(), 2);
1513 /// assert_eq!(it.next(), Some(&40));
1516 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1517 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
1518 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
1520 let mut accum = init;
1521 while let Some(x) = self.next() {
1522 accum = f(accum, x)?;
1527 /// An iterator method that applies a fallible function to each item in the
1528 /// iterator, stopping at the first error and returning that error.
1530 /// This can also be thought of as the fallible form of [`for_each()`]
1531 /// or as the stateless version of [`try_fold()`].
1533 /// [`for_each()`]: #method.for_each
1534 /// [`try_fold()`]: #method.try_fold
1539 /// use std::fs::rename;
1540 /// use std::io::{stdout, Write};
1541 /// use std::path::Path;
1543 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
1545 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
1546 /// assert!(res.is_ok());
1548 /// let mut it = data.iter().cloned();
1549 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
1550 /// assert!(res.is_err());
1551 /// // It short-circuited, so the remaining items are still in the iterator:
1552 /// assert_eq!(it.next(), Some("stale_bread.json"));
1555 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1556 fn try_for_each<F, R>(&mut self, mut f: F) -> R where
1557 Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Ok=()>
1559 self.try_fold((), move |(), x| f(x))
1562 /// An iterator method that applies a function, producing a single, final value.
1564 /// `fold()` takes two arguments: an initial value, and a closure with two
1565 /// arguments: an 'accumulator', and an element. The closure returns the value that
1566 /// the accumulator should have for the next iteration.
1568 /// The initial value is the value the accumulator will have on the first
1571 /// After applying this closure to every element of the iterator, `fold()`
1572 /// returns the accumulator.
1574 /// This operation is sometimes called 'reduce' or 'inject'.
1576 /// Folding is useful whenever you have a collection of something, and want
1577 /// to produce a single value from it.
1579 /// Note: `fold()`, and similar methods that traverse the entire iterator,
1580 /// may not terminate for infinite iterators, even on traits for which a
1581 /// result is determinable in finite time.
1588 /// let a = [1, 2, 3];
1590 /// // the sum of all of the elements of the array
1591 /// let sum = a.iter().fold(0, |acc, x| acc + x);
1593 /// assert_eq!(sum, 6);
1596 /// Let's walk through each step of the iteration here:
1598 /// | element | acc | x | result |
1599 /// |---------|-----|---|--------|
1601 /// | 1 | 0 | 1 | 1 |
1602 /// | 2 | 1 | 2 | 3 |
1603 /// | 3 | 3 | 3 | 6 |
1605 /// And so, our final result, `6`.
1607 /// It's common for people who haven't used iterators a lot to
1608 /// use a `for` loop with a list of things to build up a result. Those
1609 /// can be turned into `fold()`s:
1611 /// [`for`]: ../../book/first-edition/loops.html#for
1614 /// let numbers = [1, 2, 3, 4, 5];
1616 /// let mut result = 0;
1619 /// for i in &numbers {
1620 /// result = result + i;
1624 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1626 /// // they're the same
1627 /// assert_eq!(result, result2);
1630 #[stable(feature = "rust1", since = "1.0.0")]
1631 fn fold<B, F>(mut self, init: B, mut f: F) -> B where
1632 Self: Sized, F: FnMut(B, Self::Item) -> B,
1634 self.try_fold(init, move |acc, x| Ok::<B, !>(f(acc, x))).unwrap()
1637 /// Tests if every element of the iterator matches a predicate.
1639 /// `all()` takes a closure that returns `true` or `false`. It applies
1640 /// this closure to each element of the iterator, and if they all return
1641 /// `true`, then so does `all()`. If any of them return `false`, it
1642 /// returns `false`.
1644 /// `all()` is short-circuiting; in other words, it will stop processing
1645 /// as soon as it finds a `false`, given that no matter what else happens,
1646 /// the result will also be `false`.
1648 /// An empty iterator returns `true`.
1655 /// let a = [1, 2, 3];
1657 /// assert!(a.iter().all(|&x| x > 0));
1659 /// assert!(!a.iter().all(|&x| x > 2));
1662 /// Stopping at the first `false`:
1665 /// let a = [1, 2, 3];
1667 /// let mut iter = a.iter();
1669 /// assert!(!iter.all(|&x| x != 2));
1671 /// // we can still use `iter`, as there are more elements.
1672 /// assert_eq!(iter.next(), Some(&3));
1675 #[stable(feature = "rust1", since = "1.0.0")]
1676 fn all<F>(&mut self, mut f: F) -> bool where
1677 Self: Sized, F: FnMut(Self::Item) -> bool
1679 self.try_for_each(move |x| {
1680 if f(x) { LoopState::Continue(()) }
1681 else { LoopState::Break(()) }
1682 }) == LoopState::Continue(())
1685 /// Tests if any element of the iterator matches a predicate.
1687 /// `any()` takes a closure that returns `true` or `false`. It applies
1688 /// this closure to each element of the iterator, and if any of them return
1689 /// `true`, then so does `any()`. If they all return `false`, it
1690 /// returns `false`.
1692 /// `any()` is short-circuiting; in other words, it will stop processing
1693 /// as soon as it finds a `true`, given that no matter what else happens,
1694 /// the result will also be `true`.
1696 /// An empty iterator returns `false`.
1703 /// let a = [1, 2, 3];
1705 /// assert!(a.iter().any(|&x| x > 0));
1707 /// assert!(!a.iter().any(|&x| x > 5));
1710 /// Stopping at the first `true`:
1713 /// let a = [1, 2, 3];
1715 /// let mut iter = a.iter();
1717 /// assert!(iter.any(|&x| x != 2));
1719 /// // we can still use `iter`, as there are more elements.
1720 /// assert_eq!(iter.next(), Some(&2));
1723 #[stable(feature = "rust1", since = "1.0.0")]
1724 fn any<F>(&mut self, mut f: F) -> bool where
1726 F: FnMut(Self::Item) -> bool
1728 self.try_for_each(move |x| {
1729 if f(x) { LoopState::Break(()) }
1730 else { LoopState::Continue(()) }
1731 }) == LoopState::Break(())
1734 /// Searches for an element of an iterator that satisfies a predicate.
1736 /// `find()` takes a closure that returns `true` or `false`. It applies
1737 /// this closure to each element of the iterator, and if any of them return
1738 /// `true`, then `find()` returns [`Some(element)`]. If they all return
1739 /// `false`, it returns [`None`].
1741 /// `find()` is short-circuiting; in other words, it will stop processing
1742 /// as soon as the closure returns `true`.
1744 /// Because `find()` takes a reference, and many iterators iterate over
1745 /// references, this leads to a possibly confusing situation where the
1746 /// argument is a double reference. You can see this effect in the
1747 /// examples below, with `&&x`.
1749 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
1750 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1757 /// let a = [1, 2, 3];
1759 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1761 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1764 /// Stopping at the first `true`:
1767 /// let a = [1, 2, 3];
1769 /// let mut iter = a.iter();
1771 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1773 /// // we can still use `iter`, as there are more elements.
1774 /// assert_eq!(iter.next(), Some(&3));
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1780 P: FnMut(&Self::Item) -> bool,
1782 self.try_for_each(move |x| {
1783 if predicate(&x) { LoopState::Break(x) }
1784 else { LoopState::Continue(()) }
1788 /// Applies function to the elements of iterator and returns
1789 /// the first non-none result.
1791 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
1797 /// #![feature(iterator_find_map)]
1798 /// let a = ["lol", "NaN", "2", "5"];
1800 /// let mut first_number = a.iter().find_map(|s| s.parse().ok());
1802 /// assert_eq!(first_number, Some(2));
1805 #[unstable(feature = "iterator_find_map",
1806 reason = "unstable new API",
1808 fn find_map<B, F>(&mut self, mut f: F) -> Option<B> where
1810 F: FnMut(Self::Item) -> Option<B>,
1812 self.try_for_each(move |x| {
1814 Some(x) => LoopState::Break(x),
1815 None => LoopState::Continue(()),
1820 /// Searches for an element in an iterator, returning its index.
1822 /// `position()` takes a closure that returns `true` or `false`. It applies
1823 /// this closure to each element of the iterator, and if one of them
1824 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
1825 /// them return `false`, it returns [`None`].
1827 /// `position()` is short-circuiting; in other words, it will stop
1828 /// processing as soon as it finds a `true`.
1830 /// # Overflow Behavior
1832 /// The method does no guarding against overflows, so if there are more
1833 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
1834 /// result or panics. If debug assertions are enabled, a panic is
1839 /// This function might panic if the iterator has more than `usize::MAX`
1840 /// non-matching elements.
1842 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1843 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1844 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
1851 /// let a = [1, 2, 3];
1853 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1855 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1858 /// Stopping at the first `true`:
1861 /// let a = [1, 2, 3, 4];
1863 /// let mut iter = a.iter();
1865 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
1867 /// // we can still use `iter`, as there are more elements.
1868 /// assert_eq!(iter.next(), Some(&3));
1870 /// // The returned index depends on iterator state
1871 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
1875 #[rustc_inherit_overflow_checks]
1876 #[stable(feature = "rust1", since = "1.0.0")]
1877 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1879 P: FnMut(Self::Item) -> bool,
1881 // The addition might panic on overflow
1882 self.try_fold(0, move |i, x| {
1883 if predicate(x) { LoopState::Break(i) }
1884 else { LoopState::Continue(i + 1) }
1888 /// Searches for an element in an iterator from the right, returning its
1891 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1892 /// this closure to each element of the iterator, starting from the end,
1893 /// and if one of them returns `true`, then `rposition()` returns
1894 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
1896 /// `rposition()` is short-circuiting; in other words, it will stop
1897 /// processing as soon as it finds a `true`.
1899 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1900 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1907 /// let a = [1, 2, 3];
1909 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1911 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1914 /// Stopping at the first `true`:
1917 /// let a = [1, 2, 3];
1919 /// let mut iter = a.iter();
1921 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1923 /// // we can still use `iter`, as there are more elements.
1924 /// assert_eq!(iter.next(), Some(&1));
1927 #[stable(feature = "rust1", since = "1.0.0")]
1928 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1929 P: FnMut(Self::Item) -> bool,
1930 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1932 // No need for an overflow check here, because `ExactSizeIterator`
1933 // implies that the number of elements fits into a `usize`.
1935 self.try_rfold(n, move |i, x| {
1937 if predicate(x) { LoopState::Break(i) }
1938 else { LoopState::Continue(i) }
1942 /// Returns the maximum element of an iterator.
1944 /// If several elements are equally maximum, the last element is
1945 /// returned. If the iterator is empty, [`None`] is returned.
1947 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1954 /// let a = [1, 2, 3];
1955 /// let b: Vec<u32> = Vec::new();
1957 /// assert_eq!(a.iter().max(), Some(&3));
1958 /// assert_eq!(b.iter().max(), None);
1961 #[stable(feature = "rust1", since = "1.0.0")]
1962 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1966 // switch to y even if it is only equal, to preserve
1968 |_, x, _, y| *x <= *y)
1972 /// Returns the minimum element of an iterator.
1974 /// If several elements are equally minimum, the first element is
1975 /// returned. If the iterator is empty, [`None`] is returned.
1977 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1984 /// let a = [1, 2, 3];
1985 /// let b: Vec<u32> = Vec::new();
1987 /// assert_eq!(a.iter().min(), Some(&1));
1988 /// assert_eq!(b.iter().min(), None);
1991 #[stable(feature = "rust1", since = "1.0.0")]
1992 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1996 // only switch to y if it is strictly smaller, to
1997 // preserve stability.
1998 |_, x, _, y| *x > *y)
2002 /// Returns the element that gives the maximum value from the
2003 /// specified function.
2005 /// If several elements are equally maximum, the last element is
2006 /// returned. If the iterator is empty, [`None`] is returned.
2008 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2013 /// let a = [-3_i32, 0, 1, 5, -10];
2014 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2017 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2018 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2019 where Self: Sized, F: FnMut(&Self::Item) -> B,
2023 // switch to y even if it is only equal, to preserve
2025 |x_p, _, y_p, _| x_p <= y_p)
2029 /// Returns the element that gives the maximum value with respect to the
2030 /// specified comparison function.
2032 /// If several elements are equally maximum, the last element is
2033 /// returned. If the iterator is empty, [`None`] is returned.
2035 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2040 /// let a = [-3_i32, 0, 1, 5, -10];
2041 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2044 #[stable(feature = "iter_max_by", since = "1.15.0")]
2045 fn max_by<F>(self, mut compare: F) -> Option<Self::Item>
2046 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2050 // switch to y even if it is only equal, to preserve
2052 |_, x, _, y| Ordering::Greater != compare(x, y))
2056 /// Returns the element that gives the minimum value from the
2057 /// specified function.
2059 /// If several elements are equally minimum, the first element is
2060 /// returned. If the iterator is empty, [`None`] is returned.
2062 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2067 /// let a = [-3_i32, 0, 1, 5, -10];
2068 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2070 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2071 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2072 where Self: Sized, F: FnMut(&Self::Item) -> B,
2076 // only switch to y if it is strictly smaller, to
2077 // preserve stability.
2078 |x_p, _, y_p, _| x_p > y_p)
2082 /// Returns the element that gives the minimum value with respect to the
2083 /// specified comparison function.
2085 /// If several elements are equally minimum, the first element is
2086 /// returned. If the iterator is empty, [`None`] is returned.
2088 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2093 /// let a = [-3_i32, 0, 1, 5, -10];
2094 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2097 #[stable(feature = "iter_min_by", since = "1.15.0")]
2098 fn min_by<F>(self, mut compare: F) -> Option<Self::Item>
2099 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2103 // switch to y even if it is strictly smaller, to
2104 // preserve stability.
2105 |_, x, _, y| Ordering::Greater == compare(x, y))
2110 /// Reverses an iterator's direction.
2112 /// Usually, iterators iterate from left to right. After using `rev()`,
2113 /// an iterator will instead iterate from right to left.
2115 /// This is only possible if the iterator has an end, so `rev()` only
2116 /// works on [`DoubleEndedIterator`]s.
2118 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
2123 /// let a = [1, 2, 3];
2125 /// let mut iter = a.iter().rev();
2127 /// assert_eq!(iter.next(), Some(&3));
2128 /// assert_eq!(iter.next(), Some(&2));
2129 /// assert_eq!(iter.next(), Some(&1));
2131 /// assert_eq!(iter.next(), None);
2134 #[stable(feature = "rust1", since = "1.0.0")]
2135 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
2139 /// Converts an iterator of pairs into a pair of containers.
2141 /// `unzip()` consumes an entire iterator of pairs, producing two
2142 /// collections: one from the left elements of the pairs, and one
2143 /// from the right elements.
2145 /// This function is, in some sense, the opposite of [`zip`].
2147 /// [`zip`]: #method.zip
2154 /// let a = [(1, 2), (3, 4)];
2156 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2158 /// assert_eq!(left, [1, 3]);
2159 /// assert_eq!(right, [2, 4]);
2161 #[stable(feature = "rust1", since = "1.0.0")]
2162 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
2163 FromA: Default + Extend<A>,
2164 FromB: Default + Extend<B>,
2165 Self: Sized + Iterator<Item=(A, B)>,
2167 let mut ts: FromA = Default::default();
2168 let mut us: FromB = Default::default();
2170 self.for_each(|(t, u)| {
2178 /// Creates an iterator which [`clone`]s all of its elements.
2180 /// This is useful when you have an iterator over `&T`, but you need an
2181 /// iterator over `T`.
2183 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
2190 /// let a = [1, 2, 3];
2192 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2194 /// // cloned is the same as .map(|&x| x), for integers
2195 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2197 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2198 /// assert_eq!(v_map, vec![1, 2, 3]);
2200 #[stable(feature = "rust1", since = "1.0.0")]
2201 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2202 where Self: Sized + Iterator<Item=&'a T>, T: Clone
2207 /// Repeats an iterator endlessly.
2209 /// Instead of stopping at [`None`], the iterator will instead start again,
2210 /// from the beginning. After iterating again, it will start at the
2211 /// beginning again. And again. And again. Forever.
2213 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2220 /// let a = [1, 2, 3];
2222 /// let mut it = a.iter().cycle();
2224 /// assert_eq!(it.next(), Some(&1));
2225 /// assert_eq!(it.next(), Some(&2));
2226 /// assert_eq!(it.next(), Some(&3));
2227 /// assert_eq!(it.next(), Some(&1));
2228 /// assert_eq!(it.next(), Some(&2));
2229 /// assert_eq!(it.next(), Some(&3));
2230 /// assert_eq!(it.next(), Some(&1));
2232 #[stable(feature = "rust1", since = "1.0.0")]
2234 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
2235 Cycle{orig: self.clone(), iter: self}
2238 /// Sums the elements of an iterator.
2240 /// Takes each element, adds them together, and returns the result.
2242 /// An empty iterator returns the zero value of the type.
2246 /// When calling `sum()` and a primitive integer type is being returned, this
2247 /// method will panic if the computation overflows and debug assertions are
2255 /// let a = [1, 2, 3];
2256 /// let sum: i32 = a.iter().sum();
2258 /// assert_eq!(sum, 6);
2260 #[stable(feature = "iter_arith", since = "1.11.0")]
2261 fn sum<S>(self) -> S
2268 /// Iterates over the entire iterator, multiplying all the elements
2270 /// An empty iterator returns the one value of the type.
2274 /// When calling `product()` and a primitive integer type is being returned,
2275 /// method will panic if the computation overflows and debug assertions are
2281 /// fn factorial(n: u32) -> u32 {
2282 /// (1..).take_while(|&i| i <= n).product()
2284 /// assert_eq!(factorial(0), 1);
2285 /// assert_eq!(factorial(1), 1);
2286 /// assert_eq!(factorial(5), 120);
2288 #[stable(feature = "iter_arith", since = "1.11.0")]
2289 fn product<P>(self) -> P
2291 P: Product<Self::Item>,
2293 Product::product(self)
2296 /// Lexicographically compares the elements of this `Iterator` with those
2298 #[stable(feature = "iter_order", since = "1.5.0")]
2299 fn cmp<I>(mut self, other: I) -> Ordering where
2300 I: IntoIterator<Item = Self::Item>,
2304 let mut other = other.into_iter();
2307 let x = match self.next() {
2308 None => if other.next().is_none() {
2309 return Ordering::Equal
2311 return Ordering::Less
2316 let y = match other.next() {
2317 None => return Ordering::Greater,
2322 Ordering::Equal => (),
2323 non_eq => return non_eq,
2328 /// Lexicographically compares the elements of this `Iterator` with those
2330 #[stable(feature = "iter_order", since = "1.5.0")]
2331 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2333 Self::Item: PartialOrd<I::Item>,
2336 let mut other = other.into_iter();
2339 let x = match self.next() {
2340 None => if other.next().is_none() {
2341 return Some(Ordering::Equal)
2343 return Some(Ordering::Less)
2348 let y = match other.next() {
2349 None => return Some(Ordering::Greater),
2353 match x.partial_cmp(&y) {
2354 Some(Ordering::Equal) => (),
2355 non_eq => return non_eq,
2360 /// Determines if the elements of this `Iterator` are equal to those of
2362 #[stable(feature = "iter_order", since = "1.5.0")]
2363 fn eq<I>(mut self, other: I) -> bool where
2365 Self::Item: PartialEq<I::Item>,
2368 let mut other = other.into_iter();
2371 let x = match self.next() {
2372 None => return other.next().is_none(),
2376 let y = match other.next() {
2377 None => return false,
2381 if x != y { return false }
2385 /// Determines if the elements of this `Iterator` are unequal to those of
2387 #[stable(feature = "iter_order", since = "1.5.0")]
2388 fn ne<I>(mut self, other: I) -> bool where
2390 Self::Item: PartialEq<I::Item>,
2393 let mut other = other.into_iter();
2396 let x = match self.next() {
2397 None => return other.next().is_some(),
2401 let y = match other.next() {
2402 None => return true,
2406 if x != y { return true }
2410 /// Determines if the elements of this `Iterator` are lexicographically
2411 /// less than those of another.
2412 #[stable(feature = "iter_order", since = "1.5.0")]
2413 fn lt<I>(mut self, other: I) -> bool where
2415 Self::Item: PartialOrd<I::Item>,
2418 let mut other = other.into_iter();
2421 let x = match self.next() {
2422 None => return other.next().is_some(),
2426 let y = match other.next() {
2427 None => return false,
2431 match x.partial_cmp(&y) {
2432 Some(Ordering::Less) => return true,
2433 Some(Ordering::Equal) => (),
2434 Some(Ordering::Greater) => return false,
2435 None => return false,
2440 /// Determines if the elements of this `Iterator` are lexicographically
2441 /// less or equal to those of another.
2442 #[stable(feature = "iter_order", since = "1.5.0")]
2443 fn le<I>(mut self, other: I) -> bool where
2445 Self::Item: PartialOrd<I::Item>,
2448 let mut other = other.into_iter();
2451 let x = match self.next() {
2452 None => { other.next(); return true; },
2456 let y = match other.next() {
2457 None => return false,
2461 match x.partial_cmp(&y) {
2462 Some(Ordering::Less) => return true,
2463 Some(Ordering::Equal) => (),
2464 Some(Ordering::Greater) => return false,
2465 None => return false,
2470 /// Determines if the elements of this `Iterator` are lexicographically
2471 /// greater than those of another.
2472 #[stable(feature = "iter_order", since = "1.5.0")]
2473 fn gt<I>(mut self, other: I) -> bool where
2475 Self::Item: PartialOrd<I::Item>,
2478 let mut other = other.into_iter();
2481 let x = match self.next() {
2482 None => { other.next(); return false; },
2486 let y = match other.next() {
2487 None => return true,
2491 match x.partial_cmp(&y) {
2492 Some(Ordering::Less) => return false,
2493 Some(Ordering::Equal) => (),
2494 Some(Ordering::Greater) => return true,
2495 None => return false,
2500 /// Determines if the elements of this `Iterator` are lexicographically
2501 /// greater than or equal to those of another.
2502 #[stable(feature = "iter_order", since = "1.5.0")]
2503 fn ge<I>(mut self, other: I) -> bool where
2505 Self::Item: PartialOrd<I::Item>,
2508 let mut other = other.into_iter();
2511 let x = match self.next() {
2512 None => return other.next().is_none(),
2516 let y = match other.next() {
2517 None => return true,
2521 match x.partial_cmp(&y) {
2522 Some(Ordering::Less) => return false,
2523 Some(Ordering::Equal) => (),
2524 Some(Ordering::Greater) => return true,
2525 None => return false,
2531 /// Select an element from an iterator based on the given "projection"
2532 /// and "comparison" function.
2534 /// This is an idiosyncratic helper to try to factor out the
2535 /// commonalities of {max,min}{,_by}. In particular, this avoids
2536 /// having to implement optimizations several times.
2538 fn select_fold1<I, B, FProj, FCmp>(mut it: I,
2540 mut f_cmp: FCmp) -> Option<(B, I::Item)>
2542 FProj: FnMut(&I::Item) -> B,
2543 FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2545 // start with the first element as our selection. This avoids
2546 // having to use `Option`s inside the loop, translating to a
2547 // sizeable performance gain (6x in one case).
2548 it.next().map(|first| {
2549 let first_p = f_proj(&first);
2551 it.fold((first_p, first), |(sel_p, sel), x| {
2552 let x_p = f_proj(&x);
2553 if f_cmp(&sel_p, &sel, &x_p, &x) {
2562 #[stable(feature = "rust1", since = "1.0.0")]
2563 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2564 type Item = I::Item;
2565 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2566 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2567 fn nth(&mut self, n: usize) -> Option<Self::Item> {