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(
34 _Self="[std::ops::Range<Idx>; 1]",
35 label="if you meant to iterate between two values, remove the square brackets",
36 note="`[start..end]` is an array of one `Range`; you might have meant to have a `Range` \
37 without the brackets: `start..end`"
40 _Self="[std::ops::RangeFrom<Idx>; 1]",
41 label="if you meant to iterate from a value onwards, remove the square brackets",
42 note="`[start..]` is an array of one `RangeFrom`; you might have meant to have a \
43 `RangeFrom` without the brackets: `start..`, keeping in mind that iterating over an \
44 unbounded iterator will run forever unless you `break` or `return` from within the \
48 _Self="[std::ops::RangeTo<Idx>; 1]",
49 label="if you meant to iterate until a value, remove the square brackets and add a \
51 note="`[..end]` is an array of one `RangeTo`; you might have meant to have a bounded \
52 `Range` without the brackets: `0..end`"
55 _Self="[std::ops::RangeInclusive<Idx>; 1]",
56 label="if you meant to iterate between two values, remove the square brackets",
57 note="`[start..=end]` is an array of one `RangeInclusive`; you might have meant to have a \
58 `RangeInclusive` without the brackets: `start..=end`"
61 _Self="[std::ops::RangeToInclusive<Idx>; 1]",
62 label="if you meant to iterate until a value (including it), remove the square brackets \
63 and add a starting value",
64 note="`[..=end]` is an array of one `RangeToInclusive`; you might have meant to have a \
65 bounded `RangeInclusive` without the brackets: `0..=end`"
68 _Self="std::ops::RangeTo<Idx>",
69 label="if you meant to iterate until a value, add a starting value",
70 note="`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
71 bounded `Range`: `0..end`"
74 _Self="std::ops::RangeToInclusive<Idx>",
75 label="if you meant to iterate until a value (including it), add a starting value",
76 note="`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
77 to have a bounded `RangeInclusive`: `0..=end`"
81 label="`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
84 _Self="std::string::String",
85 label="`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
89 label="borrow the array with `&` or call `.iter()` on it to iterate over it",
90 note="arrays are not an iterators, but slices like the following are: `&[1, 2, 3]`"
94 note="if you want to iterate between `start` until a value `end`, use the exclusive range \
95 syntax `start..end` or the inclusive range syntax `start..=end`"
97 label="`{Self}` is not an iterator",
98 message="`{Self}` is not an iterator"
102 /// The type of the elements being iterated over.
103 #[stable(feature = "rust1", since = "1.0.0")]
106 /// Advances the iterator and returns the next value.
108 /// Returns [`None`] when iteration is finished. Individual iterator
109 /// implementations may choose to resume iteration, and so calling `next()`
110 /// again may or may not eventually start returning [`Some(Item)`] again at some
113 /// [`None`]: ../../std/option/enum.Option.html#variant.None
114 /// [`Some(Item)`]: ../../std/option/enum.Option.html#variant.Some
121 /// let a = [1, 2, 3];
123 /// let mut iter = a.iter();
125 /// // A call to next() returns the next value...
126 /// assert_eq!(Some(&1), iter.next());
127 /// assert_eq!(Some(&2), iter.next());
128 /// assert_eq!(Some(&3), iter.next());
130 /// // ... and then None once it's over.
131 /// assert_eq!(None, iter.next());
133 /// // More calls may or may not return None. Here, they always will.
134 /// assert_eq!(None, iter.next());
135 /// assert_eq!(None, iter.next());
137 #[stable(feature = "rust1", since = "1.0.0")]
138 fn next(&mut self) -> Option<Self::Item>;
140 /// Returns the bounds on the remaining length of the iterator.
142 /// Specifically, `size_hint()` returns a tuple where the first element
143 /// is the lower bound, and the second element is the upper bound.
145 /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
146 /// A [`None`] here means that either there is no known upper bound, or the
147 /// upper bound is larger than [`usize`].
149 /// # Implementation notes
151 /// It is not enforced that an iterator implementation yields the declared
152 /// number of elements. A buggy iterator may yield less than the lower bound
153 /// or more than the upper bound of elements.
155 /// `size_hint()` is primarily intended to be used for optimizations such as
156 /// reserving space for the elements of the iterator, but must not be
157 /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
158 /// implementation of `size_hint()` should not lead to memory safety
161 /// That said, the implementation should provide a correct estimation,
162 /// because otherwise it would be a violation of the trait's protocol.
164 /// The default implementation returns `(0, None)` which is correct for any
167 /// [`usize`]: ../../std/primitive.usize.html
168 /// [`Option`]: ../../std/option/enum.Option.html
169 /// [`None`]: ../../std/option/enum.Option.html#variant.None
176 /// let a = [1, 2, 3];
177 /// let iter = a.iter();
179 /// assert_eq!((3, Some(3)), iter.size_hint());
182 /// A more complex example:
185 /// // The even numbers from zero to ten.
186 /// let iter = (0..10).filter(|x| x % 2 == 0);
188 /// // We might iterate from zero to ten times. Knowing that it's five
189 /// // exactly wouldn't be possible without executing filter().
190 /// assert_eq!((0, Some(10)), iter.size_hint());
192 /// // Let's add five more numbers with chain()
193 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
195 /// // now both bounds are increased by five
196 /// assert_eq!((5, Some(15)), iter.size_hint());
199 /// Returning `None` for an upper bound:
202 /// // an infinite iterator has no upper bound
203 /// // and the maximum possible lower bound
206 /// assert_eq!((usize::max_value(), None), iter.size_hint());
209 #[stable(feature = "rust1", since = "1.0.0")]
210 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
212 /// Consumes the iterator, counting the number of iterations and returning it.
214 /// This method will evaluate the iterator until its [`next`] returns
215 /// [`None`]. Once [`None`] is encountered, `count()` returns the number of
216 /// times it called [`next`].
218 /// [`next`]: #tymethod.next
219 /// [`None`]: ../../std/option/enum.Option.html#variant.None
221 /// # Overflow Behavior
223 /// The method does no guarding against overflows, so counting elements of
224 /// an iterator with more than [`usize::MAX`] elements either produces the
225 /// wrong result or panics. If debug assertions are enabled, a panic is
230 /// This function might panic if the iterator has more than [`usize::MAX`]
233 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
240 /// let a = [1, 2, 3];
241 /// assert_eq!(a.iter().count(), 3);
243 /// let a = [1, 2, 3, 4, 5];
244 /// assert_eq!(a.iter().count(), 5);
247 #[rustc_inherit_overflow_checks]
248 #[stable(feature = "rust1", since = "1.0.0")]
249 fn count(self) -> usize where Self: Sized {
251 self.fold(0, |cnt, _| cnt + 1)
254 /// Consumes the iterator, returning the last element.
256 /// This method will evaluate the iterator until it returns [`None`]. While
257 /// doing so, it keeps track of the current element. After [`None`] is
258 /// returned, `last()` will then return the last element it saw.
260 /// [`None`]: ../../std/option/enum.Option.html#variant.None
267 /// let a = [1, 2, 3];
268 /// assert_eq!(a.iter().last(), Some(&3));
270 /// let a = [1, 2, 3, 4, 5];
271 /// assert_eq!(a.iter().last(), Some(&5));
274 #[stable(feature = "rust1", since = "1.0.0")]
275 fn last(self) -> Option<Self::Item> where Self: Sized {
277 for x in self { last = Some(x); }
281 /// Returns the `n`th element of the iterator.
283 /// Like most indexing operations, the count starts from zero, so `nth(0)`
284 /// returns the first value, `nth(1)` the second, and so on.
286 /// Note that all preceding elements, as well as the returned element, will be
287 /// consumed from the iterator. That means that the preceding elements will be
288 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
289 /// will return different elements.
291 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
294 /// [`None`]: ../../std/option/enum.Option.html#variant.None
301 /// let a = [1, 2, 3];
302 /// assert_eq!(a.iter().nth(1), Some(&2));
305 /// Calling `nth()` multiple times doesn't rewind the iterator:
308 /// let a = [1, 2, 3];
310 /// let mut iter = a.iter();
312 /// assert_eq!(iter.nth(1), Some(&2));
313 /// assert_eq!(iter.nth(1), None);
316 /// Returning `None` if there are less than `n + 1` elements:
319 /// let a = [1, 2, 3];
320 /// assert_eq!(a.iter().nth(10), None);
323 #[stable(feature = "rust1", since = "1.0.0")]
324 fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
326 if n == 0 { return Some(x) }
332 /// Creates an iterator starting at the same point, but stepping by
333 /// the given amount at each iteration.
335 /// Note 1: The first element of the iterator will always be returned,
336 /// regardless of the step given.
338 /// Note 2: The time at which ignored elements are pulled is not fixed.
339 /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
340 /// but is also free to behave like the sequence
341 /// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
342 /// Which way is used may change for some iterators for performance reasons.
343 /// The second way will advance the iterator earlier and may consume more items.
345 /// `advance_n_and_return_first` is the equivalent of:
347 /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
351 /// let next = iter.next();
352 /// if total_step > 1 {
353 /// iter.nth(total_step-2);
361 /// The method will panic if the given step is `0`.
368 /// let a = [0, 1, 2, 3, 4, 5];
369 /// let mut iter = a.into_iter().step_by(2);
371 /// assert_eq!(iter.next(), Some(&0));
372 /// assert_eq!(iter.next(), Some(&2));
373 /// assert_eq!(iter.next(), Some(&4));
374 /// assert_eq!(iter.next(), None);
377 #[stable(feature = "iterator_step_by", since = "1.28.0")]
378 fn step_by(self, step: usize) -> StepBy<Self> where Self: Sized {
380 StepBy{iter: self, step: step - 1, first_take: true}
383 /// Takes two iterators and creates a new iterator over both in sequence.
385 /// `chain()` will return a new iterator which will first iterate over
386 /// values from the first iterator and then over values from the second
389 /// In other words, it links two iterators together, in a chain. 🔗
396 /// let a1 = [1, 2, 3];
397 /// let a2 = [4, 5, 6];
399 /// let mut iter = a1.iter().chain(a2.iter());
401 /// assert_eq!(iter.next(), Some(&1));
402 /// assert_eq!(iter.next(), Some(&2));
403 /// assert_eq!(iter.next(), Some(&3));
404 /// assert_eq!(iter.next(), Some(&4));
405 /// assert_eq!(iter.next(), Some(&5));
406 /// assert_eq!(iter.next(), Some(&6));
407 /// assert_eq!(iter.next(), None);
410 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
411 /// anything that can be converted into an [`Iterator`], not just an
412 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
413 /// [`IntoIterator`], and so can be passed to `chain()` directly:
415 /// [`IntoIterator`]: trait.IntoIterator.html
416 /// [`Iterator`]: trait.Iterator.html
419 /// let s1 = &[1, 2, 3];
420 /// let s2 = &[4, 5, 6];
422 /// let mut iter = s1.iter().chain(s2);
424 /// assert_eq!(iter.next(), Some(&1));
425 /// assert_eq!(iter.next(), Some(&2));
426 /// assert_eq!(iter.next(), Some(&3));
427 /// assert_eq!(iter.next(), Some(&4));
428 /// assert_eq!(iter.next(), Some(&5));
429 /// assert_eq!(iter.next(), Some(&6));
430 /// assert_eq!(iter.next(), None);
433 #[stable(feature = "rust1", since = "1.0.0")]
434 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
435 Self: Sized, U: IntoIterator<Item=Self::Item>,
437 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
440 /// 'Zips up' two iterators into a single iterator of pairs.
442 /// `zip()` returns a new iterator that will iterate over two other
443 /// iterators, returning a tuple where the first element comes from the
444 /// first iterator, and the second element comes from the second iterator.
446 /// In other words, it zips two iterators together, into a single one.
448 /// If either iterator returns [`None`], [`next`] from the zipped iterator
449 /// will return [`None`]. If the first iterator returns [`None`], `zip` will
450 /// short-circuit and `next` will not be called on the second iterator.
457 /// let a1 = [1, 2, 3];
458 /// let a2 = [4, 5, 6];
460 /// let mut iter = a1.iter().zip(a2.iter());
462 /// assert_eq!(iter.next(), Some((&1, &4)));
463 /// assert_eq!(iter.next(), Some((&2, &5)));
464 /// assert_eq!(iter.next(), Some((&3, &6)));
465 /// assert_eq!(iter.next(), None);
468 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
469 /// anything that can be converted into an [`Iterator`], not just an
470 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
471 /// [`IntoIterator`], and so can be passed to `zip()` directly:
473 /// [`IntoIterator`]: trait.IntoIterator.html
474 /// [`Iterator`]: trait.Iterator.html
477 /// let s1 = &[1, 2, 3];
478 /// let s2 = &[4, 5, 6];
480 /// let mut iter = s1.iter().zip(s2);
482 /// assert_eq!(iter.next(), Some((&1, &4)));
483 /// assert_eq!(iter.next(), Some((&2, &5)));
484 /// assert_eq!(iter.next(), Some((&3, &6)));
485 /// assert_eq!(iter.next(), None);
488 /// `zip()` is often used to zip an infinite iterator to a finite one.
489 /// This works because the finite iterator will eventually return [`None`],
490 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
493 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
495 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
497 /// assert_eq!((0, 'f'), enumerate[0]);
498 /// assert_eq!((0, 'f'), zipper[0]);
500 /// assert_eq!((1, 'o'), enumerate[1]);
501 /// assert_eq!((1, 'o'), zipper[1]);
503 /// assert_eq!((2, 'o'), enumerate[2]);
504 /// assert_eq!((2, 'o'), zipper[2]);
507 /// [`enumerate`]: trait.Iterator.html#method.enumerate
508 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
509 /// [`None`]: ../../std/option/enum.Option.html#variant.None
511 #[stable(feature = "rust1", since = "1.0.0")]
512 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
513 Self: Sized, U: IntoIterator
515 Zip::new(self, other.into_iter())
518 /// Takes a closure and creates an iterator which calls that closure on each
521 /// `map()` transforms one iterator into another, by means of its argument:
522 /// something that implements `FnMut`. It produces a new iterator which
523 /// calls this closure on each element of the original iterator.
525 /// If you are good at thinking in types, you can think of `map()` like this:
526 /// If you have an iterator that gives you elements of some type `A`, and
527 /// you want an iterator of some other type `B`, you can use `map()`,
528 /// passing a closure that takes an `A` and returns a `B`.
530 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
531 /// lazy, it is best used when you're already working with other iterators.
532 /// If you're doing some sort of looping for a side effect, it's considered
533 /// more idiomatic to use [`for`] than `map()`.
535 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
542 /// let a = [1, 2, 3];
544 /// let mut iter = a.into_iter().map(|x| 2 * x);
546 /// assert_eq!(iter.next(), Some(2));
547 /// assert_eq!(iter.next(), Some(4));
548 /// assert_eq!(iter.next(), Some(6));
549 /// assert_eq!(iter.next(), None);
552 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
555 /// # #![allow(unused_must_use)]
556 /// // don't do this:
557 /// (0..5).map(|x| println!("{}", x));
559 /// // it won't even execute, as it is lazy. Rust will warn you about this.
561 /// // Instead, use for:
563 /// println!("{}", x);
567 #[stable(feature = "rust1", since = "1.0.0")]
568 fn map<B, F>(self, f: F) -> Map<Self, F> where
569 Self: Sized, F: FnMut(Self::Item) -> B,
571 Map { iter: self, f }
574 /// Calls a closure on each element of an iterator.
576 /// This is equivalent to using a [`for`] loop on the iterator, although
577 /// `break` and `continue` are not possible from a closure. It's generally
578 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
579 /// when processing items at the end of longer iterator chains. In some
580 /// cases `for_each` may also be faster than a loop, because it will use
581 /// internal iteration on adaptors like `Chain`.
583 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
590 /// use std::sync::mpsc::channel;
592 /// let (tx, rx) = channel();
593 /// (0..5).map(|x| x * 2 + 1)
594 /// .for_each(move |x| tx.send(x).unwrap());
596 /// let v: Vec<_> = rx.iter().collect();
597 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
600 /// For such a small example, a `for` loop may be cleaner, but `for_each`
601 /// might be preferable to keep a functional style with longer iterators:
604 /// (0..5).flat_map(|x| x * 100 .. x * 110)
606 /// .filter(|&(i, x)| (i + x) % 3 == 0)
607 /// .for_each(|(i, x)| println!("{}:{}", i, x));
610 #[stable(feature = "iterator_for_each", since = "1.21.0")]
611 fn for_each<F>(self, mut f: F) where
612 Self: Sized, F: FnMut(Self::Item),
614 self.fold((), move |(), item| f(item));
617 /// Creates an iterator which uses a closure to determine if an element
618 /// should be yielded.
620 /// The closure must return `true` or `false`. `filter()` creates an
621 /// iterator which calls this closure on each element. If the closure
622 /// returns `true`, then the element is returned. If the closure returns
623 /// `false`, it will try again, and call the closure on the next element,
624 /// seeing if it passes the test.
631 /// let a = [0i32, 1, 2];
633 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
635 /// assert_eq!(iter.next(), Some(&1));
636 /// assert_eq!(iter.next(), Some(&2));
637 /// assert_eq!(iter.next(), None);
640 /// Because the closure passed to `filter()` takes a reference, and many
641 /// iterators iterate over references, this leads to a possibly confusing
642 /// situation, where the type of the closure is a double reference:
645 /// let a = [0, 1, 2];
647 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
649 /// assert_eq!(iter.next(), Some(&2));
650 /// assert_eq!(iter.next(), None);
653 /// It's common to instead use destructuring on the argument to strip away
657 /// let a = [0, 1, 2];
659 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
661 /// assert_eq!(iter.next(), Some(&2));
662 /// assert_eq!(iter.next(), None);
668 /// let a = [0, 1, 2];
670 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
672 /// assert_eq!(iter.next(), Some(&2));
673 /// assert_eq!(iter.next(), None);
678 #[stable(feature = "rust1", since = "1.0.0")]
679 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
680 Self: Sized, P: FnMut(&Self::Item) -> bool,
682 Filter {iter: self, predicate }
685 /// Creates an iterator that both filters and maps.
687 /// The closure must return an [`Option<T>`]. `filter_map` creates an
688 /// iterator which calls this closure on each element. If the closure
689 /// returns [`Some(element)`][`Some`], then that element is returned. If the
690 /// closure returns [`None`], it will try again, and call the closure on the
691 /// next element, seeing if it will return [`Some`].
693 /// Why `filter_map` and not just [`filter`] and [`map`]? The key is in this
696 /// [`filter`]: #method.filter
697 /// [`map`]: #method.map
699 /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
701 /// In other words, it removes the [`Option<T>`] layer automatically. If your
702 /// mapping is already returning an [`Option<T>`] and you want to skip over
703 /// [`None`]s, then `filter_map` is much, much nicer to use.
710 /// let a = ["1", "lol", "3", "NaN", "5"];
712 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
714 /// assert_eq!(iter.next(), Some(1));
715 /// assert_eq!(iter.next(), Some(3));
716 /// assert_eq!(iter.next(), Some(5));
717 /// assert_eq!(iter.next(), None);
720 /// Here's the same example, but with [`filter`] and [`map`]:
723 /// let a = ["1", "lol", "3", "NaN", "5"];
724 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
725 /// assert_eq!(iter.next(), Some(1));
726 /// assert_eq!(iter.next(), Some(3));
727 /// assert_eq!(iter.next(), Some(5));
728 /// assert_eq!(iter.next(), None);
731 /// [`Option<T>`]: ../../std/option/enum.Option.html
732 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
733 /// [`None`]: ../../std/option/enum.Option.html#variant.None
735 #[stable(feature = "rust1", since = "1.0.0")]
736 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
737 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
739 FilterMap { iter: self, f }
742 /// Creates an iterator which gives the current iteration count as well as
745 /// The iterator returned yields pairs `(i, val)`, where `i` is the
746 /// current index of iteration and `val` is the value returned by the
749 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
750 /// different sized integer, the [`zip`] function provides similar
753 /// # Overflow Behavior
755 /// The method does no guarding against overflows, so enumerating more than
756 /// [`usize::MAX`] elements either produces the wrong result or panics. If
757 /// debug assertions are enabled, a panic is guaranteed.
761 /// The returned iterator might panic if the to-be-returned index would
762 /// overflow a [`usize`].
764 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
765 /// [`usize`]: ../../std/primitive.usize.html
766 /// [`zip`]: #method.zip
771 /// let a = ['a', 'b', 'c'];
773 /// let mut iter = a.iter().enumerate();
775 /// assert_eq!(iter.next(), Some((0, &'a')));
776 /// assert_eq!(iter.next(), Some((1, &'b')));
777 /// assert_eq!(iter.next(), Some((2, &'c')));
778 /// assert_eq!(iter.next(), None);
781 #[stable(feature = "rust1", since = "1.0.0")]
782 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
783 Enumerate { iter: self, count: 0 }
786 /// Creates an iterator which can use `peek` to look at the next element of
787 /// the iterator without consuming it.
789 /// Adds a [`peek`] method to an iterator. See its documentation for
790 /// more information.
792 /// Note that the underlying iterator is still advanced when [`peek`] is
793 /// called for the first time: In order to retrieve the next element,
794 /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
795 /// anything other than fetching the next value) of the [`next`] method
798 /// [`peek`]: struct.Peekable.html#method.peek
799 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
806 /// let xs = [1, 2, 3];
808 /// let mut iter = xs.iter().peekable();
810 /// // peek() lets us see into the future
811 /// assert_eq!(iter.peek(), Some(&&1));
812 /// assert_eq!(iter.next(), Some(&1));
814 /// assert_eq!(iter.next(), Some(&2));
816 /// // we can peek() multiple times, the iterator won't advance
817 /// assert_eq!(iter.peek(), Some(&&3));
818 /// assert_eq!(iter.peek(), Some(&&3));
820 /// assert_eq!(iter.next(), Some(&3));
822 /// // after the iterator is finished, so is peek()
823 /// assert_eq!(iter.peek(), None);
824 /// assert_eq!(iter.next(), None);
827 #[stable(feature = "rust1", since = "1.0.0")]
828 fn peekable(self) -> Peekable<Self> where Self: Sized {
829 Peekable{iter: self, peeked: None}
832 /// Creates an iterator that [`skip`]s elements based on a predicate.
834 /// [`skip`]: #method.skip
836 /// `skip_while()` takes a closure as an argument. It will call this
837 /// closure on each element of the iterator, and ignore elements
838 /// until it returns `false`.
840 /// After `false` is returned, `skip_while()`'s job is over, and the
841 /// rest of the elements are yielded.
848 /// let a = [-1i32, 0, 1];
850 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
852 /// assert_eq!(iter.next(), Some(&0));
853 /// assert_eq!(iter.next(), Some(&1));
854 /// assert_eq!(iter.next(), None);
857 /// Because the closure passed to `skip_while()` takes a reference, and many
858 /// iterators iterate over references, this leads to a possibly confusing
859 /// situation, where the type of the closure is a double reference:
862 /// let a = [-1, 0, 1];
864 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
866 /// assert_eq!(iter.next(), Some(&0));
867 /// assert_eq!(iter.next(), Some(&1));
868 /// assert_eq!(iter.next(), None);
871 /// Stopping after an initial `false`:
874 /// let a = [-1, 0, 1, -2];
876 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
878 /// assert_eq!(iter.next(), Some(&0));
879 /// assert_eq!(iter.next(), Some(&1));
881 /// // while this would have been false, since we already got a false,
882 /// // skip_while() isn't used any more
883 /// assert_eq!(iter.next(), Some(&-2));
885 /// assert_eq!(iter.next(), None);
888 #[stable(feature = "rust1", since = "1.0.0")]
889 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
890 Self: Sized, P: FnMut(&Self::Item) -> bool,
892 SkipWhile { iter: self, flag: false, predicate }
895 /// Creates an iterator that yields elements based on a predicate.
897 /// `take_while()` takes a closure as an argument. It will call this
898 /// closure on each element of the iterator, and yield elements
899 /// while it returns `true`.
901 /// After `false` is returned, `take_while()`'s job is over, and the
902 /// rest of the elements are ignored.
909 /// let a = [-1i32, 0, 1];
911 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
913 /// assert_eq!(iter.next(), Some(&-1));
914 /// assert_eq!(iter.next(), None);
917 /// Because the closure passed to `take_while()` takes a reference, and many
918 /// iterators iterate over references, this leads to a possibly confusing
919 /// situation, where the type of the closure is a double reference:
922 /// let a = [-1, 0, 1];
924 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
926 /// assert_eq!(iter.next(), Some(&-1));
927 /// assert_eq!(iter.next(), None);
930 /// Stopping after an initial `false`:
933 /// let a = [-1, 0, 1, -2];
935 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
937 /// assert_eq!(iter.next(), Some(&-1));
939 /// // We have more elements that are less than zero, but since we already
940 /// // got a false, take_while() isn't used any more
941 /// assert_eq!(iter.next(), None);
944 /// Because `take_while()` needs to look at the value in order to see if it
945 /// should be included or not, consuming iterators will see that it is
949 /// let a = [1, 2, 3, 4];
950 /// let mut iter = a.into_iter();
952 /// let result: Vec<i32> = iter.by_ref()
953 /// .take_while(|n| **n != 3)
957 /// assert_eq!(result, &[1, 2]);
959 /// let result: Vec<i32> = iter.cloned().collect();
961 /// assert_eq!(result, &[4]);
964 /// The `3` is no longer there, because it was consumed in order to see if
965 /// the iteration should stop, but wasn't placed back into the iterator or
966 /// some similar thing.
968 #[stable(feature = "rust1", since = "1.0.0")]
969 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
970 Self: Sized, P: FnMut(&Self::Item) -> bool,
972 TakeWhile { iter: self, flag: false, predicate }
975 /// Creates an iterator that skips the first `n` elements.
977 /// After they have been consumed, the rest of the elements are yielded.
984 /// let a = [1, 2, 3];
986 /// let mut iter = a.iter().skip(2);
988 /// assert_eq!(iter.next(), Some(&3));
989 /// assert_eq!(iter.next(), None);
992 #[stable(feature = "rust1", since = "1.0.0")]
993 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
994 Skip { iter: self, n }
997 /// Creates an iterator that yields its first `n` elements.
1004 /// let a = [1, 2, 3];
1006 /// let mut iter = a.iter().take(2);
1008 /// assert_eq!(iter.next(), Some(&1));
1009 /// assert_eq!(iter.next(), Some(&2));
1010 /// assert_eq!(iter.next(), None);
1013 /// `take()` is often used with an infinite iterator, to make it finite:
1016 /// let mut iter = (0..).take(3);
1018 /// assert_eq!(iter.next(), Some(0));
1019 /// assert_eq!(iter.next(), Some(1));
1020 /// assert_eq!(iter.next(), Some(2));
1021 /// assert_eq!(iter.next(), None);
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
1026 Take { iter: self, n }
1029 /// An iterator adaptor similar to [`fold`] that holds internal state and
1030 /// produces a new iterator.
1032 /// [`fold`]: #method.fold
1034 /// `scan()` takes two arguments: an initial value which seeds the internal
1035 /// state, and a closure with two arguments, the first being a mutable
1036 /// reference to the internal state and the second an iterator element.
1037 /// The closure can assign to the internal state to share state between
1040 /// On iteration, the closure will be applied to each element of the
1041 /// iterator and the return value from the closure, an [`Option`], is
1042 /// yielded by the iterator.
1044 /// [`Option`]: ../../std/option/enum.Option.html
1051 /// let a = [1, 2, 3];
1053 /// let mut iter = a.iter().scan(1, |state, &x| {
1054 /// // each iteration, we'll multiply the state by the element
1055 /// *state = *state * x;
1057 /// // then, we'll yield the negation of the state
1061 /// assert_eq!(iter.next(), Some(-1));
1062 /// assert_eq!(iter.next(), Some(-2));
1063 /// assert_eq!(iter.next(), Some(-6));
1064 /// assert_eq!(iter.next(), None);
1067 #[stable(feature = "rust1", since = "1.0.0")]
1068 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1069 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
1071 Scan { iter: self, f, state: initial_state }
1074 /// Creates an iterator that works like map, but flattens nested structure.
1076 /// The [`map`] adapter is very useful, but only when the closure
1077 /// argument produces values. If it produces an iterator instead, there's
1078 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1081 /// You can think of `flat_map(f)` as the semantic equivalent
1082 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1084 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1085 /// one item for each element, and `flat_map()`'s closure returns an
1086 /// iterator for each element.
1088 /// [`map`]: #method.map
1089 /// [`flatten`]: #method.flatten
1096 /// let words = ["alpha", "beta", "gamma"];
1098 /// // chars() returns an iterator
1099 /// let merged: String = words.iter()
1100 /// .flat_map(|s| s.chars())
1102 /// assert_eq!(merged, "alphabetagamma");
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1107 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
1109 FlatMap { inner: flatten_compat(self.map(f)) }
1112 /// Creates an iterator that flattens nested structure.
1114 /// This is useful when you have an iterator of iterators or an iterator of
1115 /// things that can be turned into iterators and you want to remove one
1116 /// level of indirection.
1123 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1124 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1125 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1128 /// Mapping and then flattening:
1131 /// let words = ["alpha", "beta", "gamma"];
1133 /// // chars() returns an iterator
1134 /// let merged: String = words.iter()
1135 /// .map(|s| s.chars())
1138 /// assert_eq!(merged, "alphabetagamma");
1141 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1142 /// in this case since it conveys intent more clearly:
1145 /// let words = ["alpha", "beta", "gamma"];
1147 /// // chars() returns an iterator
1148 /// let merged: String = words.iter()
1149 /// .flat_map(|s| s.chars())
1151 /// assert_eq!(merged, "alphabetagamma");
1154 /// Flattening once only removes one level of nesting:
1157 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1159 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1160 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1162 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1163 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1166 /// Here we see that `flatten()` does not perform a "deep" flatten.
1167 /// Instead, only one level of nesting is removed. That is, if you
1168 /// `flatten()` a three-dimensional array the result will be
1169 /// two-dimensional and not one-dimensional. To get a one-dimensional
1170 /// structure, you have to `flatten()` again.
1172 /// [`flat_map()`]: #method.flat_map
1174 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1175 fn flatten(self) -> Flatten<Self>
1176 where Self: Sized, Self::Item: IntoIterator {
1177 Flatten { inner: flatten_compat(self) }
1180 /// Creates an iterator which ends after the first [`None`].
1182 /// After an iterator returns [`None`], future calls may or may not yield
1183 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1184 /// [`None`] is given, it will always return [`None`] forever.
1186 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1187 /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
1194 /// // an iterator which alternates between Some and None
1195 /// struct Alternate {
1199 /// impl Iterator for Alternate {
1200 /// type Item = i32;
1202 /// fn next(&mut self) -> Option<i32> {
1203 /// let val = self.state;
1204 /// self.state = self.state + 1;
1206 /// // if it's even, Some(i32), else None
1207 /// if val % 2 == 0 {
1215 /// let mut iter = Alternate { state: 0 };
1217 /// // we can see our iterator going back and forth
1218 /// assert_eq!(iter.next(), Some(0));
1219 /// assert_eq!(iter.next(), None);
1220 /// assert_eq!(iter.next(), Some(2));
1221 /// assert_eq!(iter.next(), None);
1223 /// // however, once we fuse it...
1224 /// let mut iter = iter.fuse();
1226 /// assert_eq!(iter.next(), Some(4));
1227 /// assert_eq!(iter.next(), None);
1229 /// // it will always return None after the first time.
1230 /// assert_eq!(iter.next(), None);
1231 /// assert_eq!(iter.next(), None);
1232 /// assert_eq!(iter.next(), None);
1235 #[stable(feature = "rust1", since = "1.0.0")]
1236 fn fuse(self) -> Fuse<Self> where Self: Sized {
1237 Fuse{iter: self, done: false}
1240 /// Do something with each element of an iterator, passing the value on.
1242 /// When using iterators, you'll often chain several of them together.
1243 /// While working on such code, you might want to check out what's
1244 /// happening at various parts in the pipeline. To do that, insert
1245 /// a call to `inspect()`.
1247 /// It's more common for `inspect()` to be used as a debugging tool than to
1248 /// exist in your final code, but applications may find it useful in certain
1249 /// situations when errors need to be logged before being discarded.
1256 /// let a = [1, 4, 2, 3];
1258 /// // this iterator sequence is complex.
1259 /// let sum = a.iter()
1261 /// .filter(|x| x % 2 == 0)
1262 /// .fold(0, |sum, i| sum + i);
1264 /// println!("{}", sum);
1266 /// // let's add some inspect() calls to investigate what's happening
1267 /// let sum = a.iter()
1269 /// .inspect(|x| println!("about to filter: {}", x))
1270 /// .filter(|x| x % 2 == 0)
1271 /// .inspect(|x| println!("made it through filter: {}", x))
1272 /// .fold(0, |sum, i| sum + i);
1274 /// println!("{}", sum);
1277 /// This will print:
1281 /// about to filter: 1
1282 /// about to filter: 4
1283 /// made it through filter: 4
1284 /// about to filter: 2
1285 /// made it through filter: 2
1286 /// about to filter: 3
1290 /// Logging errors before discarding them:
1293 /// let lines = ["1", "2", "a"];
1295 /// let sum: i32 = lines
1297 /// .map(|line| line.parse::<i32>())
1298 /// .inspect(|num| {
1299 /// if let Err(ref e) = *num {
1300 /// println!("Parsing error: {}", e);
1303 /// .filter_map(Result::ok)
1306 /// println!("Sum: {}", sum);
1309 /// This will print:
1312 /// Parsing error: invalid digit found in string
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1318 Self: Sized, F: FnMut(&Self::Item),
1320 Inspect { iter: self, f }
1323 /// Borrows an iterator, rather than consuming it.
1325 /// This is useful to allow applying iterator adaptors while still
1326 /// retaining ownership of the original iterator.
1333 /// let a = [1, 2, 3];
1335 /// let iter = a.into_iter();
1337 /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i );
1339 /// assert_eq!(sum, 6);
1341 /// // if we try to use iter again, it won't work. The following line
1342 /// // gives "error: use of moved value: `iter`
1343 /// // assert_eq!(iter.next(), None);
1345 /// // let's try that again
1346 /// let a = [1, 2, 3];
1348 /// let mut iter = a.into_iter();
1350 /// // instead, we add in a .by_ref()
1351 /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i );
1353 /// assert_eq!(sum, 3);
1355 /// // now this is just fine:
1356 /// assert_eq!(iter.next(), Some(&3));
1357 /// assert_eq!(iter.next(), None);
1359 #[stable(feature = "rust1", since = "1.0.0")]
1360 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1362 /// Transforms an iterator into a collection.
1364 /// `collect()` can take anything iterable, and turn it into a relevant
1365 /// collection. This is one of the more powerful methods in the standard
1366 /// library, used in a variety of contexts.
1368 /// The most basic pattern in which `collect()` is used is to turn one
1369 /// collection into another. You take a collection, call [`iter`] on it,
1370 /// do a bunch of transformations, and then `collect()` at the end.
1372 /// One of the keys to `collect()`'s power is that many things you might
1373 /// not think of as 'collections' actually are. For example, a [`String`]
1374 /// is a collection of [`char`]s. And a collection of
1375 /// [`Result<T, E>`][`Result`] can be thought of as single
1376 /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1378 /// Because `collect()` is so general, it can cause problems with type
1379 /// inference. As such, `collect()` is one of the few times you'll see
1380 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1381 /// helps the inference algorithm understand specifically which collection
1382 /// you're trying to collect into.
1389 /// let a = [1, 2, 3];
1391 /// let doubled: Vec<i32> = a.iter()
1392 /// .map(|&x| x * 2)
1395 /// assert_eq!(vec![2, 4, 6], doubled);
1398 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1399 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1401 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1404 /// use std::collections::VecDeque;
1406 /// let a = [1, 2, 3];
1408 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1410 /// assert_eq!(2, doubled[0]);
1411 /// assert_eq!(4, doubled[1]);
1412 /// assert_eq!(6, doubled[2]);
1415 /// Using the 'turbofish' instead of annotating `doubled`:
1418 /// let a = [1, 2, 3];
1420 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1422 /// assert_eq!(vec![2, 4, 6], doubled);
1425 /// Because `collect()` only cares about what you're collecting into, you can
1426 /// still use a partial type hint, `_`, with the turbofish:
1429 /// let a = [1, 2, 3];
1431 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1433 /// assert_eq!(vec![2, 4, 6], doubled);
1436 /// Using `collect()` to make a [`String`]:
1439 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1441 /// let hello: String = chars.iter()
1442 /// .map(|&x| x as u8)
1443 /// .map(|x| (x + 1) as char)
1446 /// assert_eq!("hello", hello);
1449 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1450 /// see if any of them failed:
1453 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1455 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1457 /// // gives us the first error
1458 /// assert_eq!(Err("nope"), result);
1460 /// let results = [Ok(1), Ok(3)];
1462 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1464 /// // gives us the list of answers
1465 /// assert_eq!(Ok(vec![1, 3]), result);
1468 /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1469 /// [`String`]: ../../std/string/struct.String.html
1470 /// [`char`]: ../../std/primitive.char.html
1471 /// [`Result`]: ../../std/result/enum.Result.html
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1475 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1476 FromIterator::from_iter(self)
1479 /// Consumes an iterator, creating two collections from it.
1481 /// The predicate passed to `partition()` can return `true`, or `false`.
1482 /// `partition()` returns a pair, all of the elements for which it returned
1483 /// `true`, and all of the elements for which it returned `false`.
1490 /// let a = [1, 2, 3];
1492 /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1494 /// .partition(|&n| n % 2 == 0);
1496 /// assert_eq!(even, vec![2]);
1497 /// assert_eq!(odd, vec![1, 3]);
1499 #[stable(feature = "rust1", since = "1.0.0")]
1500 fn partition<B, F>(self, mut f: F) -> (B, B) where
1502 B: Default + Extend<Self::Item>,
1503 F: FnMut(&Self::Item) -> bool
1505 let mut left: B = Default::default();
1506 let mut right: B = Default::default();
1510 left.extend(Some(x))
1512 right.extend(Some(x))
1519 /// An iterator method that applies a function as long as it returns
1520 /// successfully, producing a single, final value.
1522 /// `try_fold()` takes two arguments: an initial value, and a closure with
1523 /// two arguments: an 'accumulator', and an element. The closure either
1524 /// returns successfully, with the value that the accumulator should have
1525 /// for the next iteration, or it returns failure, with an error value that
1526 /// is propagated back to the caller immediately (short-circuiting).
1528 /// The initial value is the value the accumulator will have on the first
1529 /// call. If applying the closure succeeded against every element of the
1530 /// iterator, `try_fold()` returns the final accumulator as success.
1532 /// Folding is useful whenever you have a collection of something, and want
1533 /// to produce a single value from it.
1535 /// # Note to Implementors
1537 /// Most of the other (forward) methods have default implementations in
1538 /// terms of this one, so try to implement this explicitly if it can
1539 /// do something better than the default `for` loop implementation.
1541 /// In particular, try to have this call `try_fold()` on the internal parts
1542 /// from which this iterator is composed. If multiple calls are needed,
1543 /// the `?` operator may be convenient for chaining the accumulator value
1544 /// along, but beware any invariants that need to be upheld before those
1545 /// early returns. This is a `&mut self` method, so iteration needs to be
1546 /// resumable after hitting an error here.
1553 /// let a = [1, 2, 3];
1555 /// // the checked sum of all of the elements of the array
1556 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1558 /// assert_eq!(sum, Some(6));
1561 /// Short-circuiting:
1564 /// let a = [10, 20, 30, 100, 40, 50];
1565 /// let mut it = a.iter();
1567 /// // This sum overflows when adding the 100 element
1568 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1569 /// assert_eq!(sum, None);
1571 /// // Because it short-circuited, the remaining elements are still
1572 /// // available through the iterator.
1573 /// assert_eq!(it.len(), 2);
1574 /// assert_eq!(it.next(), Some(&40));
1577 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1578 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
1579 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
1581 let mut accum = init;
1582 while let Some(x) = self.next() {
1583 accum = f(accum, x)?;
1588 /// An iterator method that applies a fallible function to each item in the
1589 /// iterator, stopping at the first error and returning that error.
1591 /// This can also be thought of as the fallible form of [`for_each()`]
1592 /// or as the stateless version of [`try_fold()`].
1594 /// [`for_each()`]: #method.for_each
1595 /// [`try_fold()`]: #method.try_fold
1600 /// use std::fs::rename;
1601 /// use std::io::{stdout, Write};
1602 /// use std::path::Path;
1604 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
1606 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
1607 /// assert!(res.is_ok());
1609 /// let mut it = data.iter().cloned();
1610 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
1611 /// assert!(res.is_err());
1612 /// // It short-circuited, so the remaining items are still in the iterator:
1613 /// assert_eq!(it.next(), Some("stale_bread.json"));
1616 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1617 fn try_for_each<F, R>(&mut self, mut f: F) -> R where
1618 Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Ok=()>
1620 self.try_fold((), move |(), x| f(x))
1623 /// An iterator method that applies a function, producing a single, final value.
1625 /// `fold()` takes two arguments: an initial value, and a closure with two
1626 /// arguments: an 'accumulator', and an element. The closure returns the value that
1627 /// the accumulator should have for the next iteration.
1629 /// The initial value is the value the accumulator will have on the first
1632 /// After applying this closure to every element of the iterator, `fold()`
1633 /// returns the accumulator.
1635 /// This operation is sometimes called 'reduce' or 'inject'.
1637 /// Folding is useful whenever you have a collection of something, and want
1638 /// to produce a single value from it.
1640 /// Note: `fold()`, and similar methods that traverse the entire iterator,
1641 /// may not terminate for infinite iterators, even on traits for which a
1642 /// result is determinable in finite time.
1649 /// let a = [1, 2, 3];
1651 /// // the sum of all of the elements of the array
1652 /// let sum = a.iter().fold(0, |acc, x| acc + x);
1654 /// assert_eq!(sum, 6);
1657 /// Let's walk through each step of the iteration here:
1659 /// | element | acc | x | result |
1660 /// |---------|-----|---|--------|
1662 /// | 1 | 0 | 1 | 1 |
1663 /// | 2 | 1 | 2 | 3 |
1664 /// | 3 | 3 | 3 | 6 |
1666 /// And so, our final result, `6`.
1668 /// It's common for people who haven't used iterators a lot to
1669 /// use a `for` loop with a list of things to build up a result. Those
1670 /// can be turned into `fold()`s:
1672 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
1675 /// let numbers = [1, 2, 3, 4, 5];
1677 /// let mut result = 0;
1680 /// for i in &numbers {
1681 /// result = result + i;
1685 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1687 /// // they're the same
1688 /// assert_eq!(result, result2);
1691 #[stable(feature = "rust1", since = "1.0.0")]
1692 fn fold<B, F>(mut self, init: B, mut f: F) -> B where
1693 Self: Sized, F: FnMut(B, Self::Item) -> B,
1695 self.try_fold(init, move |acc, x| Ok::<B, !>(f(acc, x))).unwrap()
1698 /// Tests if every element of the iterator matches a predicate.
1700 /// `all()` takes a closure that returns `true` or `false`. It applies
1701 /// this closure to each element of the iterator, and if they all return
1702 /// `true`, then so does `all()`. If any of them return `false`, it
1703 /// returns `false`.
1705 /// `all()` is short-circuiting; in other words, it will stop processing
1706 /// as soon as it finds a `false`, given that no matter what else happens,
1707 /// the result will also be `false`.
1709 /// An empty iterator returns `true`.
1716 /// let a = [1, 2, 3];
1718 /// assert!(a.iter().all(|&x| x > 0));
1720 /// assert!(!a.iter().all(|&x| x > 2));
1723 /// Stopping at the first `false`:
1726 /// let a = [1, 2, 3];
1728 /// let mut iter = a.iter();
1730 /// assert!(!iter.all(|&x| x != 2));
1732 /// // we can still use `iter`, as there are more elements.
1733 /// assert_eq!(iter.next(), Some(&3));
1736 #[stable(feature = "rust1", since = "1.0.0")]
1737 fn all<F>(&mut self, mut f: F) -> bool where
1738 Self: Sized, F: FnMut(Self::Item) -> bool
1740 self.try_for_each(move |x| {
1741 if f(x) { LoopState::Continue(()) }
1742 else { LoopState::Break(()) }
1743 }) == LoopState::Continue(())
1746 /// Tests if any element of the iterator matches a predicate.
1748 /// `any()` takes a closure that returns `true` or `false`. It applies
1749 /// this closure to each element of the iterator, and if any of them return
1750 /// `true`, then so does `any()`. If they all return `false`, it
1751 /// returns `false`.
1753 /// `any()` is short-circuiting; in other words, it will stop processing
1754 /// as soon as it finds a `true`, given that no matter what else happens,
1755 /// the result will also be `true`.
1757 /// An empty iterator returns `false`.
1764 /// let a = [1, 2, 3];
1766 /// assert!(a.iter().any(|&x| x > 0));
1768 /// assert!(!a.iter().any(|&x| x > 5));
1771 /// Stopping at the first `true`:
1774 /// let a = [1, 2, 3];
1776 /// let mut iter = a.iter();
1778 /// assert!(iter.any(|&x| x != 2));
1780 /// // we can still use `iter`, as there are more elements.
1781 /// assert_eq!(iter.next(), Some(&2));
1784 #[stable(feature = "rust1", since = "1.0.0")]
1785 fn any<F>(&mut self, mut f: F) -> bool where
1787 F: FnMut(Self::Item) -> bool
1789 self.try_for_each(move |x| {
1790 if f(x) { LoopState::Break(()) }
1791 else { LoopState::Continue(()) }
1792 }) == LoopState::Break(())
1795 /// Searches for an element of an iterator that satisfies a predicate.
1797 /// `find()` takes a closure that returns `true` or `false`. It applies
1798 /// this closure to each element of the iterator, and if any of them return
1799 /// `true`, then `find()` returns [`Some(element)`]. If they all return
1800 /// `false`, it returns [`None`].
1802 /// `find()` is short-circuiting; in other words, it will stop processing
1803 /// as soon as the closure returns `true`.
1805 /// Because `find()` takes a reference, and many iterators iterate over
1806 /// references, this leads to a possibly confusing situation where the
1807 /// argument is a double reference. You can see this effect in the
1808 /// examples below, with `&&x`.
1810 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
1811 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1818 /// let a = [1, 2, 3];
1820 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1822 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1825 /// Stopping at the first `true`:
1828 /// let a = [1, 2, 3];
1830 /// let mut iter = a.iter();
1832 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1834 /// // we can still use `iter`, as there are more elements.
1835 /// assert_eq!(iter.next(), Some(&3));
1838 #[stable(feature = "rust1", since = "1.0.0")]
1839 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1841 P: FnMut(&Self::Item) -> bool,
1843 self.try_for_each(move |x| {
1844 if predicate(&x) { LoopState::Break(x) }
1845 else { LoopState::Continue(()) }
1849 /// Applies function to the elements of iterator and returns
1850 /// the first non-none result.
1852 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
1858 /// let a = ["lol", "NaN", "2", "5"];
1860 /// let first_number = a.iter().find_map(|s| s.parse().ok());
1862 /// assert_eq!(first_number, Some(2));
1865 #[stable(feature = "iterator_find_map", since = "1.30.0")]
1866 fn find_map<B, F>(&mut self, mut f: F) -> Option<B> where
1868 F: FnMut(Self::Item) -> Option<B>,
1870 self.try_for_each(move |x| {
1872 Some(x) => LoopState::Break(x),
1873 None => LoopState::Continue(()),
1878 /// Searches for an element in an iterator, returning its index.
1880 /// `position()` takes a closure that returns `true` or `false`. It applies
1881 /// this closure to each element of the iterator, and if one of them
1882 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
1883 /// them return `false`, it returns [`None`].
1885 /// `position()` is short-circuiting; in other words, it will stop
1886 /// processing as soon as it finds a `true`.
1888 /// # Overflow Behavior
1890 /// The method does no guarding against overflows, so if there are more
1891 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
1892 /// result or panics. If debug assertions are enabled, a panic is
1897 /// This function might panic if the iterator has more than `usize::MAX`
1898 /// non-matching elements.
1900 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1901 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1902 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
1909 /// let a = [1, 2, 3];
1911 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1913 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1916 /// Stopping at the first `true`:
1919 /// let a = [1, 2, 3, 4];
1921 /// let mut iter = a.iter();
1923 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
1925 /// // we can still use `iter`, as there are more elements.
1926 /// assert_eq!(iter.next(), Some(&3));
1928 /// // The returned index depends on iterator state
1929 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
1933 #[rustc_inherit_overflow_checks]
1934 #[stable(feature = "rust1", since = "1.0.0")]
1935 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1937 P: FnMut(Self::Item) -> bool,
1939 // The addition might panic on overflow
1940 self.try_fold(0, move |i, x| {
1941 if predicate(x) { LoopState::Break(i) }
1942 else { LoopState::Continue(i + 1) }
1946 /// Searches for an element in an iterator from the right, returning its
1949 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1950 /// this closure to each element of the iterator, starting from the end,
1951 /// and if one of them returns `true`, then `rposition()` returns
1952 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
1954 /// `rposition()` is short-circuiting; in other words, it will stop
1955 /// processing as soon as it finds a `true`.
1957 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1958 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1965 /// let a = [1, 2, 3];
1967 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1969 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1972 /// Stopping at the first `true`:
1975 /// let a = [1, 2, 3];
1977 /// let mut iter = a.iter();
1979 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1981 /// // we can still use `iter`, as there are more elements.
1982 /// assert_eq!(iter.next(), Some(&1));
1985 #[stable(feature = "rust1", since = "1.0.0")]
1986 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1987 P: FnMut(Self::Item) -> bool,
1988 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1990 // No need for an overflow check here, because `ExactSizeIterator`
1991 // implies that the number of elements fits into a `usize`.
1993 self.try_rfold(n, move |i, x| {
1995 if predicate(x) { LoopState::Break(i) }
1996 else { LoopState::Continue(i) }
2000 /// Returns the maximum element of an iterator.
2002 /// If several elements are equally maximum, the last element is
2003 /// returned. If the iterator is empty, [`None`] is returned.
2005 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2012 /// let a = [1, 2, 3];
2013 /// let b: Vec<u32> = Vec::new();
2015 /// assert_eq!(a.iter().max(), Some(&3));
2016 /// assert_eq!(b.iter().max(), None);
2019 #[stable(feature = "rust1", since = "1.0.0")]
2020 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
2024 // switch to y even if it is only equal, to preserve
2026 |_, x, _, y| *x <= *y)
2030 /// Returns the minimum element of an iterator.
2032 /// If several elements are equally minimum, the first element is
2033 /// returned. If the iterator is empty, [`None`] is returned.
2035 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2042 /// let a = [1, 2, 3];
2043 /// let b: Vec<u32> = Vec::new();
2045 /// assert_eq!(a.iter().min(), Some(&1));
2046 /// assert_eq!(b.iter().min(), None);
2049 #[stable(feature = "rust1", since = "1.0.0")]
2050 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
2054 // only switch to y if it is strictly smaller, to
2055 // preserve stability.
2056 |_, x, _, y| *x > *y)
2060 /// Returns the element that gives the maximum value from the
2061 /// specified function.
2063 /// If several elements are equally maximum, the last element is
2064 /// returned. If the iterator is empty, [`None`] is returned.
2066 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2071 /// let a = [-3_i32, 0, 1, 5, -10];
2072 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2075 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2076 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2077 where Self: Sized, F: FnMut(&Self::Item) -> B,
2081 // switch to y even if it is only equal, to preserve
2083 |x_p, _, y_p, _| x_p <= y_p)
2087 /// Returns the element that gives the maximum value with respect to the
2088 /// specified comparison function.
2090 /// If several elements are equally maximum, the last element is
2091 /// returned. If the iterator is empty, [`None`] is returned.
2093 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2098 /// let a = [-3_i32, 0, 1, 5, -10];
2099 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2102 #[stable(feature = "iter_max_by", since = "1.15.0")]
2103 fn max_by<F>(self, mut compare: F) -> Option<Self::Item>
2104 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2108 // switch to y even if it is only equal, to preserve
2110 |_, x, _, y| Ordering::Greater != compare(x, y))
2114 /// Returns the element that gives the minimum value from the
2115 /// specified function.
2117 /// If several elements are equally minimum, the first element is
2118 /// returned. If the iterator is empty, [`None`] is returned.
2120 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2125 /// let a = [-3_i32, 0, 1, 5, -10];
2126 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2128 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2129 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2130 where Self: Sized, F: FnMut(&Self::Item) -> B,
2134 // only switch to y if it is strictly smaller, to
2135 // preserve stability.
2136 |x_p, _, y_p, _| x_p > y_p)
2140 /// Returns the element that gives the minimum value with respect to the
2141 /// specified comparison function.
2143 /// If several elements are equally minimum, the first element is
2144 /// returned. If the iterator is empty, [`None`] is returned.
2146 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2151 /// let a = [-3_i32, 0, 1, 5, -10];
2152 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2155 #[stable(feature = "iter_min_by", since = "1.15.0")]
2156 fn min_by<F>(self, mut compare: F) -> Option<Self::Item>
2157 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2161 // switch to y even if it is strictly smaller, to
2162 // preserve stability.
2163 |_, x, _, y| Ordering::Greater == compare(x, y))
2168 /// Reverses an iterator's direction.
2170 /// Usually, iterators iterate from left to right. After using `rev()`,
2171 /// an iterator will instead iterate from right to left.
2173 /// This is only possible if the iterator has an end, so `rev()` only
2174 /// works on [`DoubleEndedIterator`]s.
2176 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
2181 /// let a = [1, 2, 3];
2183 /// let mut iter = a.iter().rev();
2185 /// assert_eq!(iter.next(), Some(&3));
2186 /// assert_eq!(iter.next(), Some(&2));
2187 /// assert_eq!(iter.next(), Some(&1));
2189 /// assert_eq!(iter.next(), None);
2192 #[stable(feature = "rust1", since = "1.0.0")]
2193 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
2197 /// Converts an iterator of pairs into a pair of containers.
2199 /// `unzip()` consumes an entire iterator of pairs, producing two
2200 /// collections: one from the left elements of the pairs, and one
2201 /// from the right elements.
2203 /// This function is, in some sense, the opposite of [`zip`].
2205 /// [`zip`]: #method.zip
2212 /// let a = [(1, 2), (3, 4)];
2214 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2216 /// assert_eq!(left, [1, 3]);
2217 /// assert_eq!(right, [2, 4]);
2219 #[stable(feature = "rust1", since = "1.0.0")]
2220 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
2221 FromA: Default + Extend<A>,
2222 FromB: Default + Extend<B>,
2223 Self: Sized + Iterator<Item=(A, B)>,
2225 let mut ts: FromA = Default::default();
2226 let mut us: FromB = Default::default();
2228 self.for_each(|(t, u)| {
2236 /// Creates an iterator which [`clone`]s all of its elements.
2238 /// This is useful when you have an iterator over `&T`, but you need an
2239 /// iterator over `T`.
2241 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
2248 /// let a = [1, 2, 3];
2250 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2252 /// // cloned is the same as .map(|&x| x), for integers
2253 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2255 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2256 /// assert_eq!(v_map, vec![1, 2, 3]);
2258 #[stable(feature = "rust1", since = "1.0.0")]
2259 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2260 where Self: Sized + Iterator<Item=&'a T>, T: Clone
2265 /// Repeats an iterator endlessly.
2267 /// Instead of stopping at [`None`], the iterator will instead start again,
2268 /// from the beginning. After iterating again, it will start at the
2269 /// beginning again. And again. And again. Forever.
2271 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2278 /// let a = [1, 2, 3];
2280 /// let mut it = a.iter().cycle();
2282 /// assert_eq!(it.next(), Some(&1));
2283 /// assert_eq!(it.next(), Some(&2));
2284 /// assert_eq!(it.next(), Some(&3));
2285 /// assert_eq!(it.next(), Some(&1));
2286 /// assert_eq!(it.next(), Some(&2));
2287 /// assert_eq!(it.next(), Some(&3));
2288 /// assert_eq!(it.next(), Some(&1));
2290 #[stable(feature = "rust1", since = "1.0.0")]
2292 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
2293 Cycle{orig: self.clone(), iter: self}
2296 /// Sums the elements of an iterator.
2298 /// Takes each element, adds them together, and returns the result.
2300 /// An empty iterator returns the zero value of the type.
2304 /// When calling `sum()` and a primitive integer type is being returned, this
2305 /// method will panic if the computation overflows and debug assertions are
2313 /// let a = [1, 2, 3];
2314 /// let sum: i32 = a.iter().sum();
2316 /// assert_eq!(sum, 6);
2318 #[stable(feature = "iter_arith", since = "1.11.0")]
2319 fn sum<S>(self) -> S
2326 /// Iterates over the entire iterator, multiplying all the elements
2328 /// An empty iterator returns the one value of the type.
2332 /// When calling `product()` and a primitive integer type is being returned,
2333 /// method will panic if the computation overflows and debug assertions are
2339 /// fn factorial(n: u32) -> u32 {
2340 /// (1..).take_while(|&i| i <= n).product()
2342 /// assert_eq!(factorial(0), 1);
2343 /// assert_eq!(factorial(1), 1);
2344 /// assert_eq!(factorial(5), 120);
2346 #[stable(feature = "iter_arith", since = "1.11.0")]
2347 fn product<P>(self) -> P
2349 P: Product<Self::Item>,
2351 Product::product(self)
2354 /// Lexicographically compares the elements of this `Iterator` with those
2356 #[stable(feature = "iter_order", since = "1.5.0")]
2357 fn cmp<I>(mut self, other: I) -> Ordering where
2358 I: IntoIterator<Item = Self::Item>,
2362 let mut other = other.into_iter();
2365 let x = match self.next() {
2366 None => if other.next().is_none() {
2367 return Ordering::Equal
2369 return Ordering::Less
2374 let y = match other.next() {
2375 None => return Ordering::Greater,
2380 Ordering::Equal => (),
2381 non_eq => return non_eq,
2386 /// Lexicographically compares the elements of this `Iterator` with those
2388 #[stable(feature = "iter_order", since = "1.5.0")]
2389 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2391 Self::Item: PartialOrd<I::Item>,
2394 let mut other = other.into_iter();
2397 let x = match self.next() {
2398 None => if other.next().is_none() {
2399 return Some(Ordering::Equal)
2401 return Some(Ordering::Less)
2406 let y = match other.next() {
2407 None => return Some(Ordering::Greater),
2411 match x.partial_cmp(&y) {
2412 Some(Ordering::Equal) => (),
2413 non_eq => return non_eq,
2418 /// Determines if the elements of this `Iterator` are equal to those of
2420 #[stable(feature = "iter_order", since = "1.5.0")]
2421 fn eq<I>(mut self, other: I) -> bool where
2423 Self::Item: PartialEq<I::Item>,
2426 let mut other = other.into_iter();
2429 let x = match self.next() {
2430 None => return other.next().is_none(),
2434 let y = match other.next() {
2435 None => return false,
2439 if x != y { return false }
2443 /// Determines if the elements of this `Iterator` are unequal to those of
2445 #[stable(feature = "iter_order", since = "1.5.0")]
2446 fn ne<I>(mut self, other: I) -> bool where
2448 Self::Item: PartialEq<I::Item>,
2451 let mut other = other.into_iter();
2454 let x = match self.next() {
2455 None => return other.next().is_some(),
2459 let y = match other.next() {
2460 None => return true,
2464 if x != y { return true }
2468 /// Determines if the elements of this `Iterator` are lexicographically
2469 /// less than those of another.
2470 #[stable(feature = "iter_order", since = "1.5.0")]
2471 fn lt<I>(mut self, other: I) -> bool where
2473 Self::Item: PartialOrd<I::Item>,
2476 let mut other = other.into_iter();
2479 let x = match self.next() {
2480 None => return other.next().is_some(),
2484 let y = match other.next() {
2485 None => return false,
2489 match x.partial_cmp(&y) {
2490 Some(Ordering::Less) => return true,
2491 Some(Ordering::Equal) => (),
2492 Some(Ordering::Greater) => return false,
2493 None => return false,
2498 /// Determines if the elements of this `Iterator` are lexicographically
2499 /// less or equal to those of another.
2500 #[stable(feature = "iter_order", since = "1.5.0")]
2501 fn le<I>(mut self, other: I) -> bool where
2503 Self::Item: PartialOrd<I::Item>,
2506 let mut other = other.into_iter();
2509 let x = match self.next() {
2510 None => { other.next(); return true; },
2514 let y = match other.next() {
2515 None => return false,
2519 match x.partial_cmp(&y) {
2520 Some(Ordering::Less) => return true,
2521 Some(Ordering::Equal) => (),
2522 Some(Ordering::Greater) => return false,
2523 None => return false,
2528 /// Determines if the elements of this `Iterator` are lexicographically
2529 /// greater than those of another.
2530 #[stable(feature = "iter_order", since = "1.5.0")]
2531 fn gt<I>(mut self, other: I) -> bool where
2533 Self::Item: PartialOrd<I::Item>,
2536 let mut other = other.into_iter();
2539 let x = match self.next() {
2540 None => { other.next(); return false; },
2544 let y = match other.next() {
2545 None => return true,
2549 match x.partial_cmp(&y) {
2550 Some(Ordering::Less) => return false,
2551 Some(Ordering::Equal) => (),
2552 Some(Ordering::Greater) => return true,
2553 None => return false,
2558 /// Determines if the elements of this `Iterator` are lexicographically
2559 /// greater than or equal to those of another.
2560 #[stable(feature = "iter_order", since = "1.5.0")]
2561 fn ge<I>(mut self, other: I) -> bool where
2563 Self::Item: PartialOrd<I::Item>,
2566 let mut other = other.into_iter();
2569 let x = match self.next() {
2570 None => return other.next().is_none(),
2574 let y = match other.next() {
2575 None => return true,
2579 match x.partial_cmp(&y) {
2580 Some(Ordering::Less) => return false,
2581 Some(Ordering::Equal) => (),
2582 Some(Ordering::Greater) => return true,
2583 None => return false,
2589 /// Select an element from an iterator based on the given "projection"
2590 /// and "comparison" function.
2592 /// This is an idiosyncratic helper to try to factor out the
2593 /// commonalities of {max,min}{,_by}. In particular, this avoids
2594 /// having to implement optimizations several times.
2596 fn select_fold1<I, B, FProj, FCmp>(mut it: I,
2598 mut f_cmp: FCmp) -> Option<(B, I::Item)>
2600 FProj: FnMut(&I::Item) -> B,
2601 FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2603 // start with the first element as our selection. This avoids
2604 // having to use `Option`s inside the loop, translating to a
2605 // sizeable performance gain (6x in one case).
2606 it.next().map(|first| {
2607 let first_p = f_proj(&first);
2609 it.fold((first_p, first), |(sel_p, sel), x| {
2610 let x_p = f_proj(&x);
2611 if f_cmp(&sel_p, &sel, &x_p, &x) {
2620 #[stable(feature = "rust1", since = "1.0.0")]
2621 impl<I: Iterator + ?Sized> Iterator for &mut I {
2622 type Item = I::Item;
2623 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2624 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2625 fn nth(&mut self, n: usize) -> Option<Self::Item> {