1 // ignore-tidy-filelength
2 // This file almost exclusively consists of the definition of `Iterator`. We
3 // can't split that into multiple files.
5 use crate::cmp::{self, Ordering};
6 use crate::ops::{ControlFlow, Try};
8 use super::super::TrustedRandomAccess;
9 use super::super::{Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse};
10 use super::super::{FlatMap, Flatten};
11 use super::super::{FromIterator, Intersperse, IntersperseWith, Product, Sum, Zip};
13 Inspect, Map, MapWhile, Peekable, Rev, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile,
16 fn _assert_is_object_safe(_: &dyn Iterator<Item = ()>) {}
18 /// An interface for dealing with iterators.
20 /// This is the main iterator trait. For more about the concept of iterators
21 /// generally, please see the [module-level documentation]. In particular, you
22 /// may want to know how to [implement `Iterator`][impl].
24 /// [module-level documentation]: crate::iter
25 /// [impl]: crate::iter#implementing-iterator
26 #[stable(feature = "rust1", since = "1.0.0")]
27 #[rustc_on_unimplemented(
29 _Self = "[std::ops::Range<Idx>; 1]",
30 label = "if you meant to iterate between two values, remove the square brackets",
31 note = "`[start..end]` is an array of one `Range`; you might have meant to have a `Range` \
32 without the brackets: `start..end`"
35 _Self = "[std::ops::RangeFrom<Idx>; 1]",
36 label = "if you meant to iterate from a value onwards, remove the square brackets",
37 note = "`[start..]` is an array of one `RangeFrom`; you might have meant to have a \
38 `RangeFrom` without the brackets: `start..`, keeping in mind that iterating over an \
39 unbounded iterator will run forever unless you `break` or `return` from within the \
43 _Self = "[std::ops::RangeTo<Idx>; 1]",
44 label = "if you meant to iterate until a value, remove the square brackets and add a \
46 note = "`[..end]` is an array of one `RangeTo`; you might have meant to have a bounded \
47 `Range` without the brackets: `0..end`"
50 _Self = "[std::ops::RangeInclusive<Idx>; 1]",
51 label = "if you meant to iterate between two values, remove the square brackets",
52 note = "`[start..=end]` is an array of one `RangeInclusive`; you might have meant to have a \
53 `RangeInclusive` without the brackets: `start..=end`"
56 _Self = "[std::ops::RangeToInclusive<Idx>; 1]",
57 label = "if you meant to iterate until a value (including it), remove the square brackets \
58 and add a starting value",
59 note = "`[..=end]` is an array of one `RangeToInclusive`; you might have meant to have a \
60 bounded `RangeInclusive` without the brackets: `0..=end`"
63 _Self = "std::ops::RangeTo<Idx>",
64 label = "if you meant to iterate until a value, add a starting value",
65 note = "`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
66 bounded `Range`: `0..end`"
69 _Self = "std::ops::RangeToInclusive<Idx>",
70 label = "if you meant to iterate until a value (including it), add a starting value",
71 note = "`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
72 to have a bounded `RangeInclusive`: `0..=end`"
76 label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
79 _Self = "std::string::String",
80 label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
84 label = "borrow the array with `&` or call `.iter()` on it to iterate over it",
85 note = "arrays are not iterators, but slices like the following are: `&[1, 2, 3]`"
89 note = "if you want to iterate between `start` until a value `end`, use the exclusive range \
90 syntax `start..end` or the inclusive range syntax `start..=end`"
92 label = "`{Self}` is not an iterator",
93 message = "`{Self}` is not an iterator"
96 #[rustc_diagnostic_item = "Iterator"]
97 #[must_use = "iterators are lazy and do nothing unless consumed"]
99 /// The type of the elements being iterated over.
100 #[stable(feature = "rust1", since = "1.0.0")]
103 /// Advances the iterator and returns the next value.
105 /// Returns [`None`] when iteration is finished. Individual iterator
106 /// implementations may choose to resume iteration, and so calling `next()`
107 /// again may or may not eventually start returning [`Some(Item)`] again at some
110 /// [`Some(Item)`]: Some
117 /// let a = [1, 2, 3];
119 /// let mut iter = a.iter();
121 /// // A call to next() returns the next value...
122 /// assert_eq!(Some(&1), iter.next());
123 /// assert_eq!(Some(&2), iter.next());
124 /// assert_eq!(Some(&3), iter.next());
126 /// // ... and then None once it's over.
127 /// assert_eq!(None, iter.next());
129 /// // More calls may or may not return `None`. Here, they always will.
130 /// assert_eq!(None, iter.next());
131 /// assert_eq!(None, iter.next());
134 #[stable(feature = "rust1", since = "1.0.0")]
135 fn next(&mut self) -> Option<Self::Item>;
137 /// Returns the bounds on the remaining length of the iterator.
139 /// Specifically, `size_hint()` returns a tuple where the first element
140 /// is the lower bound, and the second element is the upper bound.
142 /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
143 /// A [`None`] here means that either there is no known upper bound, or the
144 /// upper bound is larger than [`usize`].
146 /// # Implementation notes
148 /// It is not enforced that an iterator implementation yields the declared
149 /// number of elements. A buggy iterator may yield less than the lower bound
150 /// or more than the upper bound of elements.
152 /// `size_hint()` is primarily intended to be used for optimizations such as
153 /// reserving space for the elements of the iterator, but must not be
154 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
155 /// implementation of `size_hint()` should not lead to memory safety
158 /// That said, the implementation should provide a correct estimation,
159 /// because otherwise it would be a violation of the trait's protocol.
161 /// The default implementation returns `(0, `[`None`]`)` which is correct for any
164 /// [`usize`]: type@usize
171 /// let a = [1, 2, 3];
172 /// let iter = a.iter();
174 /// assert_eq!((3, Some(3)), iter.size_hint());
177 /// A more complex example:
180 /// // The even numbers from zero to ten.
181 /// let iter = (0..10).filter(|x| x % 2 == 0);
183 /// // We might iterate from zero to ten times. Knowing that it's five
184 /// // exactly wouldn't be possible without executing filter().
185 /// assert_eq!((0, Some(10)), iter.size_hint());
187 /// // Let's add five more numbers with chain()
188 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
190 /// // now both bounds are increased by five
191 /// assert_eq!((5, Some(15)), iter.size_hint());
194 /// Returning `None` for an upper bound:
197 /// // an infinite iterator has no upper bound
198 /// // and the maximum possible lower bound
201 /// assert_eq!((usize::MAX, None), iter.size_hint());
204 #[stable(feature = "rust1", since = "1.0.0")]
205 fn size_hint(&self) -> (usize, Option<usize>) {
209 /// Consumes the iterator, counting the number of iterations and returning it.
211 /// This method will call [`next`] repeatedly until [`None`] is encountered,
212 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
213 /// called at least once even if the iterator does not have any elements.
215 /// [`next`]: Iterator::next
217 /// # Overflow Behavior
219 /// The method does no guarding against overflows, so counting elements of
220 /// an iterator with more than [`usize::MAX`] elements either produces the
221 /// wrong result or panics. If debug assertions are enabled, a panic is
226 /// This function might panic if the iterator has more than [`usize::MAX`]
234 /// let a = [1, 2, 3];
235 /// assert_eq!(a.iter().count(), 3);
237 /// let a = [1, 2, 3, 4, 5];
238 /// assert_eq!(a.iter().count(), 5);
241 #[stable(feature = "rust1", since = "1.0.0")]
242 fn count(self) -> usize
248 #[rustc_inherit_overflow_checks]
249 |count, _| count + 1,
253 /// Consumes the iterator, returning the last element.
255 /// This method will evaluate the iterator until it returns [`None`]. While
256 /// doing so, it keeps track of the current element. After [`None`] is
257 /// returned, `last()` will then return the last element it saw.
264 /// let a = [1, 2, 3];
265 /// assert_eq!(a.iter().last(), Some(&3));
267 /// let a = [1, 2, 3, 4, 5];
268 /// assert_eq!(a.iter().last(), Some(&5));
271 #[stable(feature = "rust1", since = "1.0.0")]
272 fn last(self) -> Option<Self::Item>
277 fn some<T>(_: Option<T>, x: T) -> Option<T> {
281 self.fold(None, some)
284 /// Advances the iterator by `n` elements.
286 /// This method will eagerly skip `n` elements by calling [`next`] up to `n`
287 /// times until [`None`] is encountered.
289 /// `advance_by(n)` will return [`Ok(())`][Ok] if the iterator successfully advances by
290 /// `n` elements, or [`Err(k)`][Err] if [`None`] is encountered, where `k` is the number
291 /// of elements the iterator is advanced by before running out of elements (i.e. the
292 /// length of the iterator). Note that `k` is always less than `n`.
294 /// Calling `advance_by(0)` does not consume any elements and always returns [`Ok(())`][Ok].
296 /// [`next`]: Iterator::next
303 /// #![feature(iter_advance_by)]
305 /// let a = [1, 2, 3, 4];
306 /// let mut iter = a.iter();
308 /// assert_eq!(iter.advance_by(2), Ok(()));
309 /// assert_eq!(iter.next(), Some(&3));
310 /// assert_eq!(iter.advance_by(0), Ok(()));
311 /// assert_eq!(iter.advance_by(100), Err(1)); // only `&4` was skipped
314 #[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")]
315 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
317 self.next().ok_or(i)?;
322 /// Returns the `n`th element of the iterator.
324 /// Like most indexing operations, the count starts from zero, so `nth(0)`
325 /// returns the first value, `nth(1)` the second, and so on.
327 /// Note that all preceding elements, as well as the returned element, will be
328 /// consumed from the iterator. That means that the preceding elements will be
329 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
330 /// will return different elements.
332 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
340 /// let a = [1, 2, 3];
341 /// assert_eq!(a.iter().nth(1), Some(&2));
344 /// Calling `nth()` multiple times doesn't rewind the iterator:
347 /// let a = [1, 2, 3];
349 /// let mut iter = a.iter();
351 /// assert_eq!(iter.nth(1), Some(&2));
352 /// assert_eq!(iter.nth(1), None);
355 /// Returning `None` if there are less than `n + 1` elements:
358 /// let a = [1, 2, 3];
359 /// assert_eq!(a.iter().nth(10), None);
362 #[stable(feature = "rust1", since = "1.0.0")]
363 fn nth(&mut self, n: usize) -> Option<Self::Item> {
364 self.advance_by(n).ok()?;
368 /// Creates an iterator starting at the same point, but stepping by
369 /// the given amount at each iteration.
371 /// Note 1: The first element of the iterator will always be returned,
372 /// regardless of the step given.
374 /// Note 2: The time at which ignored elements are pulled is not fixed.
375 /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
376 /// but is also free to behave like the sequence
377 /// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
378 /// Which way is used may change for some iterators for performance reasons.
379 /// The second way will advance the iterator earlier and may consume more items.
381 /// `advance_n_and_return_first` is the equivalent of:
383 /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
387 /// let next = iter.next();
388 /// if total_step > 1 {
389 /// iter.nth(total_step-2);
397 /// The method will panic if the given step is `0`.
404 /// let a = [0, 1, 2, 3, 4, 5];
405 /// let mut iter = a.iter().step_by(2);
407 /// assert_eq!(iter.next(), Some(&0));
408 /// assert_eq!(iter.next(), Some(&2));
409 /// assert_eq!(iter.next(), Some(&4));
410 /// assert_eq!(iter.next(), None);
413 #[stable(feature = "iterator_step_by", since = "1.28.0")]
414 fn step_by(self, step: usize) -> StepBy<Self>
418 StepBy::new(self, step)
421 /// Takes two iterators and creates a new iterator over both in sequence.
423 /// `chain()` will return a new iterator which will first iterate over
424 /// values from the first iterator and then over values from the second
427 /// In other words, it links two iterators together, in a chain. 🔗
429 /// [`once`] is commonly used to adapt a single value into a chain of
430 /// other kinds of iteration.
437 /// let a1 = [1, 2, 3];
438 /// let a2 = [4, 5, 6];
440 /// let mut iter = a1.iter().chain(a2.iter());
442 /// assert_eq!(iter.next(), Some(&1));
443 /// assert_eq!(iter.next(), Some(&2));
444 /// assert_eq!(iter.next(), Some(&3));
445 /// assert_eq!(iter.next(), Some(&4));
446 /// assert_eq!(iter.next(), Some(&5));
447 /// assert_eq!(iter.next(), Some(&6));
448 /// assert_eq!(iter.next(), None);
451 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
452 /// anything that can be converted into an [`Iterator`], not just an
453 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
454 /// [`IntoIterator`], and so can be passed to `chain()` directly:
457 /// let s1 = &[1, 2, 3];
458 /// let s2 = &[4, 5, 6];
460 /// let mut iter = s1.iter().chain(s2);
462 /// assert_eq!(iter.next(), Some(&1));
463 /// assert_eq!(iter.next(), Some(&2));
464 /// assert_eq!(iter.next(), Some(&3));
465 /// assert_eq!(iter.next(), Some(&4));
466 /// assert_eq!(iter.next(), Some(&5));
467 /// assert_eq!(iter.next(), Some(&6));
468 /// assert_eq!(iter.next(), None);
471 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
475 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
476 /// use std::os::windows::ffi::OsStrExt;
477 /// s.encode_wide().chain(std::iter::once(0)).collect()
481 /// [`once`]: crate::iter::once
482 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
484 #[stable(feature = "rust1", since = "1.0.0")]
485 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
488 U: IntoIterator<Item = Self::Item>,
490 Chain::new(self, other.into_iter())
493 /// 'Zips up' two iterators into a single iterator of pairs.
495 /// `zip()` returns a new iterator that will iterate over two other
496 /// iterators, returning a tuple where the first element comes from the
497 /// first iterator, and the second element comes from the second iterator.
499 /// In other words, it zips two iterators together, into a single one.
501 /// If either iterator returns [`None`], [`next`] from the zipped iterator
502 /// will return [`None`]. If the first iterator returns [`None`], `zip` will
503 /// short-circuit and `next` will not be called on the second iterator.
510 /// let a1 = [1, 2, 3];
511 /// let a2 = [4, 5, 6];
513 /// let mut iter = a1.iter().zip(a2.iter());
515 /// assert_eq!(iter.next(), Some((&1, &4)));
516 /// assert_eq!(iter.next(), Some((&2, &5)));
517 /// assert_eq!(iter.next(), Some((&3, &6)));
518 /// assert_eq!(iter.next(), None);
521 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
522 /// anything that can be converted into an [`Iterator`], not just an
523 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
524 /// [`IntoIterator`], and so can be passed to `zip()` directly:
527 /// let s1 = &[1, 2, 3];
528 /// let s2 = &[4, 5, 6];
530 /// let mut iter = s1.iter().zip(s2);
532 /// assert_eq!(iter.next(), Some((&1, &4)));
533 /// assert_eq!(iter.next(), Some((&2, &5)));
534 /// assert_eq!(iter.next(), Some((&3, &6)));
535 /// assert_eq!(iter.next(), None);
538 /// `zip()` is often used to zip an infinite iterator to a finite one.
539 /// This works because the finite iterator will eventually return [`None`],
540 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
543 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
545 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
547 /// assert_eq!((0, 'f'), enumerate[0]);
548 /// assert_eq!((0, 'f'), zipper[0]);
550 /// assert_eq!((1, 'o'), enumerate[1]);
551 /// assert_eq!((1, 'o'), zipper[1]);
553 /// assert_eq!((2, 'o'), enumerate[2]);
554 /// assert_eq!((2, 'o'), zipper[2]);
557 /// [`enumerate`]: Iterator::enumerate
558 /// [`next`]: Iterator::next
560 #[stable(feature = "rust1", since = "1.0.0")]
561 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
566 Zip::new(self, other.into_iter())
569 /// Creates a new iterator which places a copy of `separator` between adjacent
570 /// items of the original iterator.
572 /// In case `separator` does not implement [`Clone`] or needs to be
573 /// computed every time, use [`intersperse_with`].
580 /// #![feature(iter_intersperse)]
582 /// let mut a = [0, 1, 2].iter().intersperse(&100);
583 /// assert_eq!(a.next(), Some(&0)); // The first element from `a`.
584 /// assert_eq!(a.next(), Some(&100)); // The separator.
585 /// assert_eq!(a.next(), Some(&1)); // The next element from `a`.
586 /// assert_eq!(a.next(), Some(&100)); // The separator.
587 /// assert_eq!(a.next(), Some(&2)); // The last element from `a`.
588 /// assert_eq!(a.next(), None); // The iterator is finished.
591 /// `intersperse` can be very useful to join an iterator's items using a common element:
593 /// #![feature(iter_intersperse)]
595 /// let hello = ["Hello", "World", "!"].iter().copied().intersperse(" ").collect::<String>();
596 /// assert_eq!(hello, "Hello World !");
599 /// [`Clone`]: crate::clone::Clone
600 /// [`intersperse_with`]: Iterator::intersperse_with
602 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
603 fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
608 Intersperse::new(self, separator)
611 /// Creates a new iterator which places an item generated by `separator`
612 /// between adjacent items of the original iterator.
614 /// The closure will be called exactly once each time an item is placed
615 /// between two adjacent items from the underlying iterator; specifically,
616 /// the closure is not called if the underlying iterator yields less than
617 /// two items and after the last item is yielded.
619 /// If the iterator's item implements [`Clone`], it may be easier to use
627 /// #![feature(iter_intersperse)]
629 /// #[derive(PartialEq, Debug)]
630 /// struct NotClone(usize);
632 /// let v = vec![NotClone(0), NotClone(1), NotClone(2)];
633 /// let mut it = v.into_iter().intersperse_with(|| NotClone(99));
635 /// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`.
636 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
637 /// assert_eq!(it.next(), Some(NotClone(1))); // The next element from `v`.
638 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
639 /// assert_eq!(it.next(), Some(NotClone(2))); // The last element from from `v`.
640 /// assert_eq!(it.next(), None); // The iterator is finished.
643 /// `intersperse_with` can be used in situations where the separator needs
646 /// #![feature(iter_intersperse)]
648 /// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();
650 /// // The closure mutably borrows its context to generate an item.
651 /// let mut happy_emojis = [" ❤️ ", " 😀 "].iter().copied();
652 /// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
654 /// let result = src.intersperse_with(separator).collect::<String>();
655 /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
657 /// [`Clone`]: crate::clone::Clone
658 /// [`intersperse`]: Iterator::intersperse
660 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
661 fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
664 G: FnMut() -> Self::Item,
666 IntersperseWith::new(self, separator)
669 /// Takes a closure and creates an iterator which calls that closure on each
672 /// `map()` transforms one iterator into another, by means of its argument:
673 /// something that implements [`FnMut`]. It produces a new iterator which
674 /// calls this closure on each element of the original iterator.
676 /// If you are good at thinking in types, you can think of `map()` like this:
677 /// If you have an iterator that gives you elements of some type `A`, and
678 /// you want an iterator of some other type `B`, you can use `map()`,
679 /// passing a closure that takes an `A` and returns a `B`.
681 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
682 /// lazy, it is best used when you're already working with other iterators.
683 /// If you're doing some sort of looping for a side effect, it's considered
684 /// more idiomatic to use [`for`] than `map()`.
686 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
687 /// [`FnMut`]: crate::ops::FnMut
694 /// let a = [1, 2, 3];
696 /// let mut iter = a.iter().map(|x| 2 * x);
698 /// assert_eq!(iter.next(), Some(2));
699 /// assert_eq!(iter.next(), Some(4));
700 /// assert_eq!(iter.next(), Some(6));
701 /// assert_eq!(iter.next(), None);
704 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
707 /// # #![allow(unused_must_use)]
708 /// // don't do this:
709 /// (0..5).map(|x| println!("{}", x));
711 /// // it won't even execute, as it is lazy. Rust will warn you about this.
713 /// // Instead, use for:
715 /// println!("{}", x);
719 #[stable(feature = "rust1", since = "1.0.0")]
720 fn map<B, F>(self, f: F) -> Map<Self, F>
723 F: FnMut(Self::Item) -> B,
728 /// Calls a closure on each element of an iterator.
730 /// This is equivalent to using a [`for`] loop on the iterator, although
731 /// `break` and `continue` are not possible from a closure. It's generally
732 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
733 /// when processing items at the end of longer iterator chains. In some
734 /// cases `for_each` may also be faster than a loop, because it will use
735 /// internal iteration on adaptors like `Chain`.
737 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
744 /// use std::sync::mpsc::channel;
746 /// let (tx, rx) = channel();
747 /// (0..5).map(|x| x * 2 + 1)
748 /// .for_each(move |x| tx.send(x).unwrap());
750 /// let v: Vec<_> = rx.iter().collect();
751 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
754 /// For such a small example, a `for` loop may be cleaner, but `for_each`
755 /// might be preferable to keep a functional style with longer iterators:
758 /// (0..5).flat_map(|x| x * 100 .. x * 110)
760 /// .filter(|&(i, x)| (i + x) % 3 == 0)
761 /// .for_each(|(i, x)| println!("{}:{}", i, x));
764 #[stable(feature = "iterator_for_each", since = "1.21.0")]
765 fn for_each<F>(self, f: F)
768 F: FnMut(Self::Item),
771 fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
772 move |(), item| f(item)
775 self.fold((), call(f));
778 /// Creates an iterator which uses a closure to determine if an element
779 /// should be yielded.
781 /// Given an element the closure must return `true` or `false`. The returned
782 /// iterator will yield only the elements for which the closure returns
790 /// let a = [0i32, 1, 2];
792 /// let mut iter = a.iter().filter(|x| x.is_positive());
794 /// assert_eq!(iter.next(), Some(&1));
795 /// assert_eq!(iter.next(), Some(&2));
796 /// assert_eq!(iter.next(), None);
799 /// Because the closure passed to `filter()` takes a reference, and many
800 /// iterators iterate over references, this leads to a possibly confusing
801 /// situation, where the type of the closure is a double reference:
804 /// let a = [0, 1, 2];
806 /// let mut iter = a.iter().filter(|x| **x > 1); // need two *s!
808 /// assert_eq!(iter.next(), Some(&2));
809 /// assert_eq!(iter.next(), None);
812 /// It's common to instead use destructuring on the argument to strip away
816 /// let a = [0, 1, 2];
818 /// let mut iter = a.iter().filter(|&x| *x > 1); // both & and *
820 /// assert_eq!(iter.next(), Some(&2));
821 /// assert_eq!(iter.next(), None);
827 /// let a = [0, 1, 2];
829 /// let mut iter = a.iter().filter(|&&x| x > 1); // two &s
831 /// assert_eq!(iter.next(), Some(&2));
832 /// assert_eq!(iter.next(), None);
837 /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
839 #[stable(feature = "rust1", since = "1.0.0")]
840 fn filter<P>(self, predicate: P) -> Filter<Self, P>
843 P: FnMut(&Self::Item) -> bool,
845 Filter::new(self, predicate)
848 /// Creates an iterator that both filters and maps.
850 /// The returned iterator yields only the `value`s for which the supplied
851 /// closure returns `Some(value)`.
853 /// `filter_map` can be used to make chains of [`filter`] and [`map`] more
854 /// concise. The example below shows how a `map().filter().map()` can be
855 /// shortened to a single call to `filter_map`.
857 /// [`filter`]: Iterator::filter
858 /// [`map`]: Iterator::map
865 /// let a = ["1", "two", "NaN", "four", "5"];
867 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
869 /// assert_eq!(iter.next(), Some(1));
870 /// assert_eq!(iter.next(), Some(5));
871 /// assert_eq!(iter.next(), None);
874 /// Here's the same example, but with [`filter`] and [`map`]:
877 /// let a = ["1", "two", "NaN", "four", "5"];
878 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
879 /// assert_eq!(iter.next(), Some(1));
880 /// assert_eq!(iter.next(), Some(5));
881 /// assert_eq!(iter.next(), None);
884 #[stable(feature = "rust1", since = "1.0.0")]
885 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
888 F: FnMut(Self::Item) -> Option<B>,
890 FilterMap::new(self, f)
893 /// Creates an iterator which gives the current iteration count as well as
896 /// The iterator returned yields pairs `(i, val)`, where `i` is the
897 /// current index of iteration and `val` is the value returned by the
900 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
901 /// different sized integer, the [`zip`] function provides similar
904 /// # Overflow Behavior
906 /// The method does no guarding against overflows, so enumerating more than
907 /// [`usize::MAX`] elements either produces the wrong result or panics. If
908 /// debug assertions are enabled, a panic is guaranteed.
912 /// The returned iterator might panic if the to-be-returned index would
913 /// overflow a [`usize`].
915 /// [`usize`]: type@usize
916 /// [`zip`]: Iterator::zip
921 /// let a = ['a', 'b', 'c'];
923 /// let mut iter = a.iter().enumerate();
925 /// assert_eq!(iter.next(), Some((0, &'a')));
926 /// assert_eq!(iter.next(), Some((1, &'b')));
927 /// assert_eq!(iter.next(), Some((2, &'c')));
928 /// assert_eq!(iter.next(), None);
931 #[stable(feature = "rust1", since = "1.0.0")]
932 fn enumerate(self) -> Enumerate<Self>
939 /// Creates an iterator which can use [`peek`] to look at the next element of
940 /// the iterator without consuming it.
942 /// Adds a [`peek`] method to an iterator. See its documentation for
943 /// more information.
945 /// Note that the underlying iterator is still advanced when [`peek`] is
946 /// called for the first time: In order to retrieve the next element,
947 /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
948 /// anything other than fetching the next value) of the [`next`] method
951 /// [`peek`]: Peekable::peek
952 /// [`next`]: Iterator::next
959 /// let xs = [1, 2, 3];
961 /// let mut iter = xs.iter().peekable();
963 /// // peek() lets us see into the future
964 /// assert_eq!(iter.peek(), Some(&&1));
965 /// assert_eq!(iter.next(), Some(&1));
967 /// assert_eq!(iter.next(), Some(&2));
969 /// // we can peek() multiple times, the iterator won't advance
970 /// assert_eq!(iter.peek(), Some(&&3));
971 /// assert_eq!(iter.peek(), Some(&&3));
973 /// assert_eq!(iter.next(), Some(&3));
975 /// // after the iterator is finished, so is peek()
976 /// assert_eq!(iter.peek(), None);
977 /// assert_eq!(iter.next(), None);
980 #[stable(feature = "rust1", since = "1.0.0")]
981 fn peekable(self) -> Peekable<Self>
988 /// Creates an iterator that [`skip`]s elements based on a predicate.
990 /// [`skip`]: Iterator::skip
992 /// `skip_while()` takes a closure as an argument. It will call this
993 /// closure on each element of the iterator, and ignore elements
994 /// until it returns `false`.
996 /// After `false` is returned, `skip_while()`'s job is over, and the
997 /// rest of the elements are yielded.
1004 /// let a = [-1i32, 0, 1];
1006 /// let mut iter = a.iter().skip_while(|x| x.is_negative());
1008 /// assert_eq!(iter.next(), Some(&0));
1009 /// assert_eq!(iter.next(), Some(&1));
1010 /// assert_eq!(iter.next(), None);
1013 /// Because the closure passed to `skip_while()` takes a reference, and many
1014 /// iterators iterate over references, this leads to a possibly confusing
1015 /// situation, where the type of the closure is a double reference:
1018 /// let a = [-1, 0, 1];
1020 /// let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s!
1022 /// assert_eq!(iter.next(), Some(&0));
1023 /// assert_eq!(iter.next(), Some(&1));
1024 /// assert_eq!(iter.next(), None);
1027 /// Stopping after an initial `false`:
1030 /// let a = [-1, 0, 1, -2];
1032 /// let mut iter = a.iter().skip_while(|x| **x < 0);
1034 /// assert_eq!(iter.next(), Some(&0));
1035 /// assert_eq!(iter.next(), Some(&1));
1037 /// // while this would have been false, since we already got a false,
1038 /// // skip_while() isn't used any more
1039 /// assert_eq!(iter.next(), Some(&-2));
1041 /// assert_eq!(iter.next(), None);
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
1048 P: FnMut(&Self::Item) -> bool,
1050 SkipWhile::new(self, predicate)
1053 /// Creates an iterator that yields elements based on a predicate.
1055 /// `take_while()` takes a closure as an argument. It will call this
1056 /// closure on each element of the iterator, and yield elements
1057 /// while it returns `true`.
1059 /// After `false` is returned, `take_while()`'s job is over, and the
1060 /// rest of the elements are ignored.
1067 /// let a = [-1i32, 0, 1];
1069 /// let mut iter = a.iter().take_while(|x| x.is_negative());
1071 /// assert_eq!(iter.next(), Some(&-1));
1072 /// assert_eq!(iter.next(), None);
1075 /// Because the closure passed to `take_while()` takes a reference, and many
1076 /// iterators iterate over references, this leads to a possibly confusing
1077 /// situation, where the type of the closure is a double reference:
1080 /// let a = [-1, 0, 1];
1082 /// let mut iter = a.iter().take_while(|x| **x < 0); // need two *s!
1084 /// assert_eq!(iter.next(), Some(&-1));
1085 /// assert_eq!(iter.next(), None);
1088 /// Stopping after an initial `false`:
1091 /// let a = [-1, 0, 1, -2];
1093 /// let mut iter = a.iter().take_while(|x| **x < 0);
1095 /// assert_eq!(iter.next(), Some(&-1));
1097 /// // We have more elements that are less than zero, but since we already
1098 /// // got a false, take_while() isn't used any more
1099 /// assert_eq!(iter.next(), None);
1102 /// Because `take_while()` needs to look at the value in order to see if it
1103 /// should be included or not, consuming iterators will see that it is
1107 /// let a = [1, 2, 3, 4];
1108 /// let mut iter = a.iter();
1110 /// let result: Vec<i32> = iter.by_ref()
1111 /// .take_while(|n| **n != 3)
1115 /// assert_eq!(result, &[1, 2]);
1117 /// let result: Vec<i32> = iter.cloned().collect();
1119 /// assert_eq!(result, &[4]);
1122 /// The `3` is no longer there, because it was consumed in order to see if
1123 /// the iteration should stop, but wasn't placed back into the iterator.
1125 #[stable(feature = "rust1", since = "1.0.0")]
1126 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1129 P: FnMut(&Self::Item) -> bool,
1131 TakeWhile::new(self, predicate)
1134 /// Creates an iterator that both yields elements based on a predicate and maps.
1136 /// `map_while()` takes a closure as an argument. It will call this
1137 /// closure on each element of the iterator, and yield elements
1138 /// while it returns [`Some(_)`][`Some`].
1145 /// #![feature(iter_map_while)]
1146 /// let a = [-1i32, 4, 0, 1];
1148 /// let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));
1150 /// assert_eq!(iter.next(), Some(-16));
1151 /// assert_eq!(iter.next(), Some(4));
1152 /// assert_eq!(iter.next(), None);
1155 /// Here's the same example, but with [`take_while`] and [`map`]:
1157 /// [`take_while`]: Iterator::take_while
1158 /// [`map`]: Iterator::map
1161 /// let a = [-1i32, 4, 0, 1];
1163 /// let mut iter = a.iter()
1164 /// .map(|x| 16i32.checked_div(*x))
1165 /// .take_while(|x| x.is_some())
1166 /// .map(|x| x.unwrap());
1168 /// assert_eq!(iter.next(), Some(-16));
1169 /// assert_eq!(iter.next(), Some(4));
1170 /// assert_eq!(iter.next(), None);
1173 /// Stopping after an initial [`None`]:
1176 /// #![feature(iter_map_while)]
1177 /// use std::convert::TryFrom;
1179 /// let a = [0, 1, 2, -3, 4, 5, -6];
1181 /// let iter = a.iter().map_while(|x| u32::try_from(*x).ok());
1182 /// let vec = iter.collect::<Vec<_>>();
1184 /// // We have more elements which could fit in u32 (4, 5), but `map_while` returned `None` for `-3`
1185 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
1186 /// assert_eq!(vec, vec![0, 1, 2]);
1189 /// Because `map_while()` needs to look at the value in order to see if it
1190 /// should be included or not, consuming iterators will see that it is
1194 /// #![feature(iter_map_while)]
1195 /// use std::convert::TryFrom;
1197 /// let a = [1, 2, -3, 4];
1198 /// let mut iter = a.iter();
1200 /// let result: Vec<u32> = iter.by_ref()
1201 /// .map_while(|n| u32::try_from(*n).ok())
1204 /// assert_eq!(result, &[1, 2]);
1206 /// let result: Vec<i32> = iter.cloned().collect();
1208 /// assert_eq!(result, &[4]);
1211 /// The `-3` is no longer there, because it was consumed in order to see if
1212 /// the iteration should stop, but wasn't placed back into the iterator.
1214 /// Note that unlike [`take_while`] this iterator is **not** fused.
1215 /// It is also not specified what this iterator returns after the first [`None`] is returned.
1216 /// If you need fused iterator, use [`fuse`].
1218 /// [`fuse`]: Iterator::fuse
1220 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
1221 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1224 P: FnMut(Self::Item) -> Option<B>,
1226 MapWhile::new(self, predicate)
1229 /// Creates an iterator that skips the first `n` elements.
1231 /// `skip(n)` skips elements until `n` elements are skipped or the end of the
1232 /// iterator is reached (whichever happens first). After that, all the remaining
1233 /// elements are yielded. In particular, if the original iterator is too short,
1234 /// then the returned iterator is empty.
1236 /// Rather than overriding this method directly, instead override the `nth` method.
1243 /// let a = [1, 2, 3];
1245 /// let mut iter = a.iter().skip(2);
1247 /// assert_eq!(iter.next(), Some(&3));
1248 /// assert_eq!(iter.next(), None);
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 fn skip(self, n: usize) -> Skip<Self>
1259 /// Creates an iterator that yields the first `n` elements, or fewer
1260 /// if the underlying iterator ends sooner.
1262 /// `take(n)` yields elements until `n` elements are yielded or the end of
1263 /// the iterator is reached (whichever happens first).
1264 /// The returned iterator is a prefix of length `n` if the original iterator
1265 /// contains at least `n` elements, otherwise it contains all of the
1266 /// (fewer than `n`) elements of the original iterator.
1273 /// let a = [1, 2, 3];
1275 /// let mut iter = a.iter().take(2);
1277 /// assert_eq!(iter.next(), Some(&1));
1278 /// assert_eq!(iter.next(), Some(&2));
1279 /// assert_eq!(iter.next(), None);
1282 /// `take()` is often used with an infinite iterator, to make it finite:
1285 /// let mut iter = (0..).take(3);
1287 /// assert_eq!(iter.next(), Some(0));
1288 /// assert_eq!(iter.next(), Some(1));
1289 /// assert_eq!(iter.next(), Some(2));
1290 /// assert_eq!(iter.next(), None);
1293 /// If less than `n` elements are available,
1294 /// `take` will limit itself to the size of the underlying iterator:
1297 /// let v = vec![1, 2];
1298 /// let mut iter = v.into_iter().take(5);
1299 /// assert_eq!(iter.next(), Some(1));
1300 /// assert_eq!(iter.next(), Some(2));
1301 /// assert_eq!(iter.next(), None);
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 fn take(self, n: usize) -> Take<Self>
1312 /// An iterator adaptor similar to [`fold`] that holds internal state and
1313 /// produces a new iterator.
1315 /// [`fold`]: Iterator::fold
1317 /// `scan()` takes two arguments: an initial value which seeds the internal
1318 /// state, and a closure with two arguments, the first being a mutable
1319 /// reference to the internal state and the second an iterator element.
1320 /// The closure can assign to the internal state to share state between
1323 /// On iteration, the closure will be applied to each element of the
1324 /// iterator and the return value from the closure, an [`Option`], is
1325 /// yielded by the iterator.
1332 /// let a = [1, 2, 3];
1334 /// let mut iter = a.iter().scan(1, |state, &x| {
1335 /// // each iteration, we'll multiply the state by the element
1336 /// *state = *state * x;
1338 /// // then, we'll yield the negation of the state
1342 /// assert_eq!(iter.next(), Some(-1));
1343 /// assert_eq!(iter.next(), Some(-2));
1344 /// assert_eq!(iter.next(), Some(-6));
1345 /// assert_eq!(iter.next(), None);
1348 #[stable(feature = "rust1", since = "1.0.0")]
1349 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1352 F: FnMut(&mut St, Self::Item) -> Option<B>,
1354 Scan::new(self, initial_state, f)
1357 /// Creates an iterator that works like map, but flattens nested structure.
1359 /// The [`map`] adapter is very useful, but only when the closure
1360 /// argument produces values. If it produces an iterator instead, there's
1361 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1364 /// You can think of `flat_map(f)` as the semantic equivalent
1365 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1367 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1368 /// one item for each element, and `flat_map()`'s closure returns an
1369 /// iterator for each element.
1371 /// [`map`]: Iterator::map
1372 /// [`flatten`]: Iterator::flatten
1379 /// let words = ["alpha", "beta", "gamma"];
1381 /// // chars() returns an iterator
1382 /// let merged: String = words.iter()
1383 /// .flat_map(|s| s.chars())
1385 /// assert_eq!(merged, "alphabetagamma");
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1393 F: FnMut(Self::Item) -> U,
1395 FlatMap::new(self, f)
1398 /// Creates an iterator that flattens nested structure.
1400 /// This is useful when you have an iterator of iterators or an iterator of
1401 /// things that can be turned into iterators and you want to remove one
1402 /// level of indirection.
1409 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1410 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1411 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1414 /// Mapping and then flattening:
1417 /// let words = ["alpha", "beta", "gamma"];
1419 /// // chars() returns an iterator
1420 /// let merged: String = words.iter()
1421 /// .map(|s| s.chars())
1424 /// assert_eq!(merged, "alphabetagamma");
1427 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1428 /// in this case since it conveys intent more clearly:
1431 /// let words = ["alpha", "beta", "gamma"];
1433 /// // chars() returns an iterator
1434 /// let merged: String = words.iter()
1435 /// .flat_map(|s| s.chars())
1437 /// assert_eq!(merged, "alphabetagamma");
1440 /// Flattening only removes one level of nesting at a time:
1443 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1445 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1446 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1448 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1449 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1452 /// Here we see that `flatten()` does not perform a "deep" flatten.
1453 /// Instead, only one level of nesting is removed. That is, if you
1454 /// `flatten()` a three-dimensional array, the result will be
1455 /// two-dimensional and not one-dimensional. To get a one-dimensional
1456 /// structure, you have to `flatten()` again.
1458 /// [`flat_map()`]: Iterator::flat_map
1460 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1461 fn flatten(self) -> Flatten<Self>
1464 Self::Item: IntoIterator,
1469 /// Creates an iterator which ends after the first [`None`].
1471 /// After an iterator returns [`None`], future calls may or may not yield
1472 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1473 /// [`None`] is given, it will always return [`None`] forever.
1475 /// [`Some(T)`]: Some
1482 /// // an iterator which alternates between Some and None
1483 /// struct Alternate {
1487 /// impl Iterator for Alternate {
1488 /// type Item = i32;
1490 /// fn next(&mut self) -> Option<i32> {
1491 /// let val = self.state;
1492 /// self.state = self.state + 1;
1494 /// // if it's even, Some(i32), else None
1495 /// if val % 2 == 0 {
1503 /// let mut iter = Alternate { state: 0 };
1505 /// // we can see our iterator going back and forth
1506 /// assert_eq!(iter.next(), Some(0));
1507 /// assert_eq!(iter.next(), None);
1508 /// assert_eq!(iter.next(), Some(2));
1509 /// assert_eq!(iter.next(), None);
1511 /// // however, once we fuse it...
1512 /// let mut iter = iter.fuse();
1514 /// assert_eq!(iter.next(), Some(4));
1515 /// assert_eq!(iter.next(), None);
1517 /// // it will always return `None` after the first time.
1518 /// assert_eq!(iter.next(), None);
1519 /// assert_eq!(iter.next(), None);
1520 /// assert_eq!(iter.next(), None);
1523 #[stable(feature = "rust1", since = "1.0.0")]
1524 fn fuse(self) -> Fuse<Self>
1531 /// Does something with each element of an iterator, passing the value on.
1533 /// When using iterators, you'll often chain several of them together.
1534 /// While working on such code, you might want to check out what's
1535 /// happening at various parts in the pipeline. To do that, insert
1536 /// a call to `inspect()`.
1538 /// It's more common for `inspect()` to be used as a debugging tool than to
1539 /// exist in your final code, but applications may find it useful in certain
1540 /// situations when errors need to be logged before being discarded.
1547 /// let a = [1, 4, 2, 3];
1549 /// // this iterator sequence is complex.
1550 /// let sum = a.iter()
1552 /// .filter(|x| x % 2 == 0)
1553 /// .fold(0, |sum, i| sum + i);
1555 /// println!("{}", sum);
1557 /// // let's add some inspect() calls to investigate what's happening
1558 /// let sum = a.iter()
1560 /// .inspect(|x| println!("about to filter: {}", x))
1561 /// .filter(|x| x % 2 == 0)
1562 /// .inspect(|x| println!("made it through filter: {}", x))
1563 /// .fold(0, |sum, i| sum + i);
1565 /// println!("{}", sum);
1568 /// This will print:
1572 /// about to filter: 1
1573 /// about to filter: 4
1574 /// made it through filter: 4
1575 /// about to filter: 2
1576 /// made it through filter: 2
1577 /// about to filter: 3
1581 /// Logging errors before discarding them:
1584 /// let lines = ["1", "2", "a"];
1586 /// let sum: i32 = lines
1588 /// .map(|line| line.parse::<i32>())
1589 /// .inspect(|num| {
1590 /// if let Err(ref e) = *num {
1591 /// println!("Parsing error: {}", e);
1594 /// .filter_map(Result::ok)
1597 /// println!("Sum: {}", sum);
1600 /// This will print:
1603 /// Parsing error: invalid digit found in string
1607 #[stable(feature = "rust1", since = "1.0.0")]
1608 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1611 F: FnMut(&Self::Item),
1613 Inspect::new(self, f)
1616 /// Borrows an iterator, rather than consuming it.
1618 /// This is useful to allow applying iterator adaptors while still
1619 /// retaining ownership of the original iterator.
1626 /// let a = [1, 2, 3];
1628 /// let iter = a.iter();
1630 /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i);
1632 /// assert_eq!(sum, 6);
1634 /// // if we try to use iter again, it won't work. The following line
1635 /// // gives "error: use of moved value: `iter`
1636 /// // assert_eq!(iter.next(), None);
1638 /// // let's try that again
1639 /// let a = [1, 2, 3];
1641 /// let mut iter = a.iter();
1643 /// // instead, we add in a .by_ref()
1644 /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i);
1646 /// assert_eq!(sum, 3);
1648 /// // now this is just fine:
1649 /// assert_eq!(iter.next(), Some(&3));
1650 /// assert_eq!(iter.next(), None);
1652 #[stable(feature = "rust1", since = "1.0.0")]
1653 fn by_ref(&mut self) -> &mut Self
1660 /// Transforms an iterator into a collection.
1662 /// `collect()` can take anything iterable, and turn it into a relevant
1663 /// collection. This is one of the more powerful methods in the standard
1664 /// library, used in a variety of contexts.
1666 /// The most basic pattern in which `collect()` is used is to turn one
1667 /// collection into another. You take a collection, call [`iter`] on it,
1668 /// do a bunch of transformations, and then `collect()` at the end.
1670 /// `collect()` can also create instances of types that are not typical
1671 /// collections. For example, a [`String`] can be built from [`char`]s,
1672 /// and an iterator of [`Result<T, E>`][`Result`] items can be collected
1673 /// into `Result<Collection<T>, E>`. See the examples below for more.
1675 /// Because `collect()` is so general, it can cause problems with type
1676 /// inference. As such, `collect()` is one of the few times you'll see
1677 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1678 /// helps the inference algorithm understand specifically which collection
1679 /// you're trying to collect into.
1686 /// let a = [1, 2, 3];
1688 /// let doubled: Vec<i32> = a.iter()
1689 /// .map(|&x| x * 2)
1692 /// assert_eq!(vec![2, 4, 6], doubled);
1695 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1696 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1698 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1701 /// use std::collections::VecDeque;
1703 /// let a = [1, 2, 3];
1705 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1707 /// assert_eq!(2, doubled[0]);
1708 /// assert_eq!(4, doubled[1]);
1709 /// assert_eq!(6, doubled[2]);
1712 /// Using the 'turbofish' instead of annotating `doubled`:
1715 /// let a = [1, 2, 3];
1717 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1719 /// assert_eq!(vec![2, 4, 6], doubled);
1722 /// Because `collect()` only cares about what you're collecting into, you can
1723 /// still use a partial type hint, `_`, with the turbofish:
1726 /// let a = [1, 2, 3];
1728 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1730 /// assert_eq!(vec![2, 4, 6], doubled);
1733 /// Using `collect()` to make a [`String`]:
1736 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1738 /// let hello: String = chars.iter()
1739 /// .map(|&x| x as u8)
1740 /// .map(|x| (x + 1) as char)
1743 /// assert_eq!("hello", hello);
1746 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1747 /// see if any of them failed:
1750 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1752 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1754 /// // gives us the first error
1755 /// assert_eq!(Err("nope"), result);
1757 /// let results = [Ok(1), Ok(3)];
1759 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1761 /// // gives us the list of answers
1762 /// assert_eq!(Ok(vec![1, 3]), result);
1765 /// [`iter`]: Iterator::next
1766 /// [`String`]: ../../std/string/struct.String.html
1767 /// [`char`]: type@char
1769 #[stable(feature = "rust1", since = "1.0.0")]
1770 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1771 fn collect<B: FromIterator<Self::Item>>(self) -> B
1775 FromIterator::from_iter(self)
1778 /// Consumes an iterator, creating two collections from it.
1780 /// The predicate passed to `partition()` can return `true`, or `false`.
1781 /// `partition()` returns a pair, all of the elements for which it returned
1782 /// `true`, and all of the elements for which it returned `false`.
1784 /// See also [`is_partitioned()`] and [`partition_in_place()`].
1786 /// [`is_partitioned()`]: Iterator::is_partitioned
1787 /// [`partition_in_place()`]: Iterator::partition_in_place
1794 /// let a = [1, 2, 3];
1796 /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1798 /// .partition(|&n| n % 2 == 0);
1800 /// assert_eq!(even, vec![2]);
1801 /// assert_eq!(odd, vec![1, 3]);
1803 #[stable(feature = "rust1", since = "1.0.0")]
1804 fn partition<B, F>(self, f: F) -> (B, B)
1807 B: Default + Extend<Self::Item>,
1808 F: FnMut(&Self::Item) -> bool,
1811 fn extend<'a, T, B: Extend<T>>(
1812 mut f: impl FnMut(&T) -> bool + 'a,
1815 ) -> impl FnMut((), T) + 'a {
1820 right.extend_one(x);
1825 let mut left: B = Default::default();
1826 let mut right: B = Default::default();
1828 self.fold((), extend(f, &mut left, &mut right));
1833 /// Reorders the elements of this iterator *in-place* according to the given predicate,
1834 /// such that all those that return `true` precede all those that return `false`.
1835 /// Returns the number of `true` elements found.
1837 /// The relative order of partitioned items is not maintained.
1839 /// See also [`is_partitioned()`] and [`partition()`].
1841 /// [`is_partitioned()`]: Iterator::is_partitioned
1842 /// [`partition()`]: Iterator::partition
1847 /// #![feature(iter_partition_in_place)]
1849 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
1851 /// // Partition in-place between evens and odds
1852 /// let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0);
1854 /// assert_eq!(i, 3);
1855 /// assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens
1856 /// assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds
1858 #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")]
1859 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
1861 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
1862 P: FnMut(&T) -> bool,
1864 // FIXME: should we worry about the count overflowing? The only way to have more than
1865 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
1867 // These closure "factory" functions exist to avoid genericity in `Self`.
1871 predicate: &'a mut impl FnMut(&T) -> bool,
1872 true_count: &'a mut usize,
1873 ) -> impl FnMut(&&mut T) -> bool + 'a {
1875 let p = predicate(&**x);
1876 *true_count += p as usize;
1882 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
1883 move |x| predicate(&**x)
1886 // Repeatedly find the first `false` and swap it with the last `true`.
1887 let mut true_count = 0;
1888 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
1889 if let Some(tail) = self.rfind(is_true(predicate)) {
1890 crate::mem::swap(head, tail);
1899 /// Checks if the elements of this iterator are partitioned according to the given predicate,
1900 /// such that all those that return `true` precede all those that return `false`.
1902 /// See also [`partition()`] and [`partition_in_place()`].
1904 /// [`partition()`]: Iterator::partition
1905 /// [`partition_in_place()`]: Iterator::partition_in_place
1910 /// #![feature(iter_is_partitioned)]
1912 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
1913 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
1915 #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")]
1916 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
1919 P: FnMut(Self::Item) -> bool,
1921 // Either all items test `true`, or the first clause stops at `false`
1922 // and we check that there are no more `true` items after that.
1923 self.all(&mut predicate) || !self.any(predicate)
1926 /// An iterator method that applies a function as long as it returns
1927 /// successfully, producing a single, final value.
1929 /// `try_fold()` takes two arguments: an initial value, and a closure with
1930 /// two arguments: an 'accumulator', and an element. The closure either
1931 /// returns successfully, with the value that the accumulator should have
1932 /// for the next iteration, or it returns failure, with an error value that
1933 /// is propagated back to the caller immediately (short-circuiting).
1935 /// The initial value is the value the accumulator will have on the first
1936 /// call. If applying the closure succeeded against every element of the
1937 /// iterator, `try_fold()` returns the final accumulator as success.
1939 /// Folding is useful whenever you have a collection of something, and want
1940 /// to produce a single value from it.
1942 /// # Note to Implementors
1944 /// Several of the other (forward) methods have default implementations in
1945 /// terms of this one, so try to implement this explicitly if it can
1946 /// do something better than the default `for` loop implementation.
1948 /// In particular, try to have this call `try_fold()` on the internal parts
1949 /// from which this iterator is composed. If multiple calls are needed,
1950 /// the `?` operator may be convenient for chaining the accumulator value
1951 /// along, but beware any invariants that need to be upheld before those
1952 /// early returns. This is a `&mut self` method, so iteration needs to be
1953 /// resumable after hitting an error here.
1960 /// let a = [1, 2, 3];
1962 /// // the checked sum of all of the elements of the array
1963 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1965 /// assert_eq!(sum, Some(6));
1968 /// Short-circuiting:
1971 /// let a = [10, 20, 30, 100, 40, 50];
1972 /// let mut it = a.iter();
1974 /// // This sum overflows when adding the 100 element
1975 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1976 /// assert_eq!(sum, None);
1978 /// // Because it short-circuited, the remaining elements are still
1979 /// // available through the iterator.
1980 /// assert_eq!(it.len(), 2);
1981 /// assert_eq!(it.next(), Some(&40));
1984 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1985 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
1988 F: FnMut(B, Self::Item) -> R,
1991 let mut accum = init;
1992 while let Some(x) = self.next() {
1993 accum = f(accum, x)?;
1998 /// An iterator method that applies a fallible function to each item in the
1999 /// iterator, stopping at the first error and returning that error.
2001 /// This can also be thought of as the fallible form of [`for_each()`]
2002 /// or as the stateless version of [`try_fold()`].
2004 /// [`for_each()`]: Iterator::for_each
2005 /// [`try_fold()`]: Iterator::try_fold
2010 /// use std::fs::rename;
2011 /// use std::io::{stdout, Write};
2012 /// use std::path::Path;
2014 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
2016 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
2017 /// assert!(res.is_ok());
2019 /// let mut it = data.iter().cloned();
2020 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
2021 /// assert!(res.is_err());
2022 /// // It short-circuited, so the remaining items are still in the iterator:
2023 /// assert_eq!(it.next(), Some("stale_bread.json"));
2026 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2027 fn try_for_each<F, R>(&mut self, f: F) -> R
2030 F: FnMut(Self::Item) -> R,
2034 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
2038 self.try_fold((), call(f))
2041 /// Folds every element into an accumulator by applying an operation,
2042 /// returning the final result.
2044 /// `fold()` takes two arguments: an initial value, and a closure with two
2045 /// arguments: an 'accumulator', and an element. The closure returns the value that
2046 /// the accumulator should have for the next iteration.
2048 /// The initial value is the value the accumulator will have on the first
2051 /// After applying this closure to every element of the iterator, `fold()`
2052 /// returns the accumulator.
2054 /// This operation is sometimes called 'reduce' or 'inject'.
2056 /// Folding is useful whenever you have a collection of something, and want
2057 /// to produce a single value from it.
2059 /// Note: `fold()`, and similar methods that traverse the entire iterator,
2060 /// may not terminate for infinite iterators, even on traits for which a
2061 /// result is determinable in finite time.
2063 /// Note: [`reduce()`] can be used to use the first element as the initial
2064 /// value, if the accumulator type and item type is the same.
2066 /// # Note to Implementors
2068 /// Several of the other (forward) methods have default implementations in
2069 /// terms of this one, so try to implement this explicitly if it can
2070 /// do something better than the default `for` loop implementation.
2072 /// In particular, try to have this call `fold()` on the internal parts
2073 /// from which this iterator is composed.
2080 /// let a = [1, 2, 3];
2082 /// // the sum of all of the elements of the array
2083 /// let sum = a.iter().fold(0, |acc, x| acc + x);
2085 /// assert_eq!(sum, 6);
2088 /// Let's walk through each step of the iteration here:
2090 /// | element | acc | x | result |
2091 /// |---------|-----|---|--------|
2093 /// | 1 | 0 | 1 | 1 |
2094 /// | 2 | 1 | 2 | 3 |
2095 /// | 3 | 3 | 3 | 6 |
2097 /// And so, our final result, `6`.
2099 /// It's common for people who haven't used iterators a lot to
2100 /// use a `for` loop with a list of things to build up a result. Those
2101 /// can be turned into `fold()`s:
2103 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
2106 /// let numbers = [1, 2, 3, 4, 5];
2108 /// let mut result = 0;
2111 /// for i in &numbers {
2112 /// result = result + i;
2116 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2118 /// // they're the same
2119 /// assert_eq!(result, result2);
2122 /// [`reduce()`]: Iterator::reduce
2123 #[doc(alias = "reduce")]
2124 #[doc(alias = "inject")]
2126 #[stable(feature = "rust1", since = "1.0.0")]
2127 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2130 F: FnMut(B, Self::Item) -> B,
2132 let mut accum = init;
2133 while let Some(x) = self.next() {
2134 accum = f(accum, x);
2139 /// Reduces the elements to a single one, by repeatedly applying a reducing
2142 /// If the iterator is empty, returns [`None`]; otherwise, returns the
2143 /// result of the reduction.
2145 /// For iterators with at least one element, this is the same as [`fold()`]
2146 /// with the first element of the iterator as the initial value, folding
2147 /// every subsequent element into it.
2149 /// [`fold()`]: Iterator::fold
2153 /// Find the maximum value:
2156 /// fn find_max<I>(iter: I) -> Option<I::Item>
2157 /// where I: Iterator,
2160 /// iter.reduce(|a, b| {
2161 /// if a >= b { a } else { b }
2164 /// let a = [10, 20, 5, -23, 0];
2165 /// let b: [u32; 0] = [];
2167 /// assert_eq!(find_max(a.iter()), Some(&20));
2168 /// assert_eq!(find_max(b.iter()), None);
2171 #[stable(feature = "iterator_fold_self", since = "1.51.0")]
2172 fn reduce<F>(mut self, f: F) -> Option<Self::Item>
2175 F: FnMut(Self::Item, Self::Item) -> Self::Item,
2177 let first = self.next()?;
2178 Some(self.fold(first, f))
2181 /// Tests if every element of the iterator matches a predicate.
2183 /// `all()` takes a closure that returns `true` or `false`. It applies
2184 /// this closure to each element of the iterator, and if they all return
2185 /// `true`, then so does `all()`. If any of them return `false`, it
2186 /// returns `false`.
2188 /// `all()` is short-circuiting; in other words, it will stop processing
2189 /// as soon as it finds a `false`, given that no matter what else happens,
2190 /// the result will also be `false`.
2192 /// An empty iterator returns `true`.
2199 /// let a = [1, 2, 3];
2201 /// assert!(a.iter().all(|&x| x > 0));
2203 /// assert!(!a.iter().all(|&x| x > 2));
2206 /// Stopping at the first `false`:
2209 /// let a = [1, 2, 3];
2211 /// let mut iter = a.iter();
2213 /// assert!(!iter.all(|&x| x != 2));
2215 /// // we can still use `iter`, as there are more elements.
2216 /// assert_eq!(iter.next(), Some(&3));
2218 #[doc(alias = "every")]
2220 #[stable(feature = "rust1", since = "1.0.0")]
2221 fn all<F>(&mut self, f: F) -> bool
2224 F: FnMut(Self::Item) -> bool,
2227 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2229 if f(x) { ControlFlow::CONTINUE } else { ControlFlow::BREAK }
2232 self.try_fold((), check(f)) == ControlFlow::CONTINUE
2235 /// Tests if any element of the iterator matches a predicate.
2237 /// `any()` takes a closure that returns `true` or `false`. It applies
2238 /// this closure to each element of the iterator, and if any of them return
2239 /// `true`, then so does `any()`. If they all return `false`, it
2240 /// returns `false`.
2242 /// `any()` is short-circuiting; in other words, it will stop processing
2243 /// as soon as it finds a `true`, given that no matter what else happens,
2244 /// the result will also be `true`.
2246 /// An empty iterator returns `false`.
2253 /// let a = [1, 2, 3];
2255 /// assert!(a.iter().any(|&x| x > 0));
2257 /// assert!(!a.iter().any(|&x| x > 5));
2260 /// Stopping at the first `true`:
2263 /// let a = [1, 2, 3];
2265 /// let mut iter = a.iter();
2267 /// assert!(iter.any(|&x| x != 2));
2269 /// // we can still use `iter`, as there are more elements.
2270 /// assert_eq!(iter.next(), Some(&2));
2273 #[stable(feature = "rust1", since = "1.0.0")]
2274 fn any<F>(&mut self, f: F) -> bool
2277 F: FnMut(Self::Item) -> bool,
2280 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2282 if f(x) { ControlFlow::BREAK } else { ControlFlow::CONTINUE }
2286 self.try_fold((), check(f)) == ControlFlow::BREAK
2289 /// Searches for an element of an iterator that satisfies a predicate.
2291 /// `find()` takes a closure that returns `true` or `false`. It applies
2292 /// this closure to each element of the iterator, and if any of them return
2293 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2294 /// `false`, it returns [`None`].
2296 /// `find()` is short-circuiting; in other words, it will stop processing
2297 /// as soon as the closure returns `true`.
2299 /// Because `find()` takes a reference, and many iterators iterate over
2300 /// references, this leads to a possibly confusing situation where the
2301 /// argument is a double reference. You can see this effect in the
2302 /// examples below, with `&&x`.
2304 /// [`Some(element)`]: Some
2311 /// let a = [1, 2, 3];
2313 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2315 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2318 /// Stopping at the first `true`:
2321 /// let a = [1, 2, 3];
2323 /// let mut iter = a.iter();
2325 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
2327 /// // we can still use `iter`, as there are more elements.
2328 /// assert_eq!(iter.next(), Some(&3));
2331 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2333 #[stable(feature = "rust1", since = "1.0.0")]
2334 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2337 P: FnMut(&Self::Item) -> bool,
2340 fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
2342 if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::CONTINUE }
2346 self.try_fold((), check(predicate)).break_value()
2349 /// Applies function to the elements of iterator and returns
2350 /// the first non-none result.
2352 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2357 /// let a = ["lol", "NaN", "2", "5"];
2359 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2361 /// assert_eq!(first_number, Some(2));
2364 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2365 fn find_map<B, F>(&mut self, f: F) -> Option<B>
2368 F: FnMut(Self::Item) -> Option<B>,
2371 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> ControlFlow<B> {
2372 move |(), x| match f(x) {
2373 Some(x) => ControlFlow::Break(x),
2374 None => ControlFlow::CONTINUE,
2378 self.try_fold((), check(f)).break_value()
2381 /// Applies function to the elements of iterator and returns
2382 /// the first true result or the first error.
2387 /// #![feature(try_find)]
2389 /// let a = ["1", "2", "lol", "NaN", "5"];
2391 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
2392 /// Ok(s.parse::<i32>()? == search)
2395 /// let result = a.iter().try_find(|&&s| is_my_num(s, 2));
2396 /// assert_eq!(result, Ok(Some(&"2")));
2398 /// let result = a.iter().try_find(|&&s| is_my_num(s, 5));
2399 /// assert!(result.is_err());
2402 #[unstable(feature = "try_find", reason = "new API", issue = "63178")]
2403 fn try_find<F, R>(&mut self, f: F) -> Result<Option<Self::Item>, R::Error>
2406 F: FnMut(&Self::Item) -> R,
2410 fn check<F, T, R>(mut f: F) -> impl FnMut((), T) -> ControlFlow<Result<T, R::Error>>
2415 move |(), x| match f(&x).into_result() {
2416 Ok(false) => ControlFlow::CONTINUE,
2417 Ok(true) => ControlFlow::Break(Ok(x)),
2418 Err(x) => ControlFlow::Break(Err(x)),
2422 self.try_fold((), check(f)).break_value().transpose()
2425 /// Searches for an element in an iterator, returning its index.
2427 /// `position()` takes a closure that returns `true` or `false`. It applies
2428 /// this closure to each element of the iterator, and if one of them
2429 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
2430 /// them return `false`, it returns [`None`].
2432 /// `position()` is short-circuiting; in other words, it will stop
2433 /// processing as soon as it finds a `true`.
2435 /// # Overflow Behavior
2437 /// The method does no guarding against overflows, so if there are more
2438 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
2439 /// result or panics. If debug assertions are enabled, a panic is
2444 /// This function might panic if the iterator has more than `usize::MAX`
2445 /// non-matching elements.
2447 /// [`Some(index)`]: Some
2454 /// let a = [1, 2, 3];
2456 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
2458 /// assert_eq!(a.iter().position(|&x| x == 5), None);
2461 /// Stopping at the first `true`:
2464 /// let a = [1, 2, 3, 4];
2466 /// let mut iter = a.iter();
2468 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
2470 /// // we can still use `iter`, as there are more elements.
2471 /// assert_eq!(iter.next(), Some(&3));
2473 /// // The returned index depends on iterator state
2474 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
2478 #[stable(feature = "rust1", since = "1.0.0")]
2479 fn position<P>(&mut self, predicate: P) -> Option<usize>
2482 P: FnMut(Self::Item) -> bool,
2486 mut predicate: impl FnMut(T) -> bool,
2487 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
2488 #[rustc_inherit_overflow_checks]
2490 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i + 1) }
2494 self.try_fold(0, check(predicate)).break_value()
2497 /// Searches for an element in an iterator from the right, returning its
2500 /// `rposition()` takes a closure that returns `true` or `false`. It applies
2501 /// this closure to each element of the iterator, starting from the end,
2502 /// and if one of them returns `true`, then `rposition()` returns
2503 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
2505 /// `rposition()` is short-circuiting; in other words, it will stop
2506 /// processing as soon as it finds a `true`.
2508 /// [`Some(index)`]: Some
2515 /// let a = [1, 2, 3];
2517 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
2519 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
2522 /// Stopping at the first `true`:
2525 /// let a = [1, 2, 3];
2527 /// let mut iter = a.iter();
2529 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
2531 /// // we can still use `iter`, as there are more elements.
2532 /// assert_eq!(iter.next(), Some(&1));
2535 #[stable(feature = "rust1", since = "1.0.0")]
2536 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
2538 P: FnMut(Self::Item) -> bool,
2539 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
2541 // No need for an overflow check here, because `ExactSizeIterator`
2542 // implies that the number of elements fits into a `usize`.
2545 mut predicate: impl FnMut(T) -> bool,
2546 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
2549 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i) }
2554 self.try_rfold(n, check(predicate)).break_value()
2557 /// Returns the maximum element of an iterator.
2559 /// If several elements are equally maximum, the last element is
2560 /// returned. If the iterator is empty, [`None`] is returned.
2567 /// let a = [1, 2, 3];
2568 /// let b: Vec<u32> = Vec::new();
2570 /// assert_eq!(a.iter().max(), Some(&3));
2571 /// assert_eq!(b.iter().max(), None);
2574 #[stable(feature = "rust1", since = "1.0.0")]
2575 fn max(self) -> Option<Self::Item>
2580 self.max_by(Ord::cmp)
2583 /// Returns the minimum element of an iterator.
2585 /// If several elements are equally minimum, the first element is
2586 /// returned. If the iterator is empty, [`None`] is returned.
2593 /// let a = [1, 2, 3];
2594 /// let b: Vec<u32> = Vec::new();
2596 /// assert_eq!(a.iter().min(), Some(&1));
2597 /// assert_eq!(b.iter().min(), None);
2600 #[stable(feature = "rust1", since = "1.0.0")]
2601 fn min(self) -> Option<Self::Item>
2606 self.min_by(Ord::cmp)
2609 /// Returns the element that gives the maximum value from the
2610 /// specified function.
2612 /// If several elements are equally maximum, the last element is
2613 /// returned. If the iterator is empty, [`None`] is returned.
2618 /// let a = [-3_i32, 0, 1, 5, -10];
2619 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2622 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2623 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2626 F: FnMut(&Self::Item) -> B,
2629 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2634 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2638 let (_, x) = self.map(key(f)).max_by(compare)?;
2642 /// Returns the element that gives the maximum value with respect to the
2643 /// specified comparison function.
2645 /// If several elements are equally maximum, the last element is
2646 /// returned. If the iterator is empty, [`None`] is returned.
2651 /// let a = [-3_i32, 0, 1, 5, -10];
2652 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2655 #[stable(feature = "iter_max_by", since = "1.15.0")]
2656 fn max_by<F>(self, compare: F) -> Option<Self::Item>
2659 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2662 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2663 move |x, y| cmp::max_by(x, y, &mut compare)
2666 self.reduce(fold(compare))
2669 /// Returns the element that gives the minimum value from the
2670 /// specified function.
2672 /// If several elements are equally minimum, the first element is
2673 /// returned. If the iterator is empty, [`None`] is returned.
2678 /// let a = [-3_i32, 0, 1, 5, -10];
2679 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2682 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2683 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2686 F: FnMut(&Self::Item) -> B,
2689 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2694 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2698 let (_, x) = self.map(key(f)).min_by(compare)?;
2702 /// Returns the element that gives the minimum value with respect to the
2703 /// specified comparison function.
2705 /// If several elements are equally minimum, the first element is
2706 /// returned. If the iterator is empty, [`None`] is returned.
2711 /// let a = [-3_i32, 0, 1, 5, -10];
2712 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2715 #[stable(feature = "iter_min_by", since = "1.15.0")]
2716 fn min_by<F>(self, compare: F) -> Option<Self::Item>
2719 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2722 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2723 move |x, y| cmp::min_by(x, y, &mut compare)
2726 self.reduce(fold(compare))
2729 /// Reverses an iterator's direction.
2731 /// Usually, iterators iterate from left to right. After using `rev()`,
2732 /// an iterator will instead iterate from right to left.
2734 /// This is only possible if the iterator has an end, so `rev()` only
2735 /// works on [`DoubleEndedIterator`]s.
2740 /// let a = [1, 2, 3];
2742 /// let mut iter = a.iter().rev();
2744 /// assert_eq!(iter.next(), Some(&3));
2745 /// assert_eq!(iter.next(), Some(&2));
2746 /// assert_eq!(iter.next(), Some(&1));
2748 /// assert_eq!(iter.next(), None);
2751 #[doc(alias = "reverse")]
2752 #[stable(feature = "rust1", since = "1.0.0")]
2753 fn rev(self) -> Rev<Self>
2755 Self: Sized + DoubleEndedIterator,
2760 /// Converts an iterator of pairs into a pair of containers.
2762 /// `unzip()` consumes an entire iterator of pairs, producing two
2763 /// collections: one from the left elements of the pairs, and one
2764 /// from the right elements.
2766 /// This function is, in some sense, the opposite of [`zip`].
2768 /// [`zip`]: Iterator::zip
2775 /// let a = [(1, 2), (3, 4)];
2777 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2779 /// assert_eq!(left, [1, 3]);
2780 /// assert_eq!(right, [2, 4]);
2782 #[stable(feature = "rust1", since = "1.0.0")]
2783 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
2785 FromA: Default + Extend<A>,
2786 FromB: Default + Extend<B>,
2787 Self: Sized + Iterator<Item = (A, B)>,
2789 fn extend<'a, A, B>(
2790 ts: &'a mut impl Extend<A>,
2791 us: &'a mut impl Extend<B>,
2792 ) -> impl FnMut((), (A, B)) + 'a {
2799 let mut ts: FromA = Default::default();
2800 let mut us: FromB = Default::default();
2802 let (lower_bound, _) = self.size_hint();
2803 if lower_bound > 0 {
2804 ts.extend_reserve(lower_bound);
2805 us.extend_reserve(lower_bound);
2808 self.fold((), extend(&mut ts, &mut us));
2813 /// Creates an iterator which copies all of its elements.
2815 /// This is useful when you have an iterator over `&T`, but you need an
2816 /// iterator over `T`.
2823 /// let a = [1, 2, 3];
2825 /// let v_copied: Vec<_> = a.iter().copied().collect();
2827 /// // copied is the same as .map(|&x| x)
2828 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2830 /// assert_eq!(v_copied, vec![1, 2, 3]);
2831 /// assert_eq!(v_map, vec![1, 2, 3]);
2833 #[stable(feature = "iter_copied", since = "1.36.0")]
2834 fn copied<'a, T: 'a>(self) -> Copied<Self>
2836 Self: Sized + Iterator<Item = &'a T>,
2842 /// Creates an iterator which [`clone`]s all of its elements.
2844 /// This is useful when you have an iterator over `&T`, but you need an
2845 /// iterator over `T`.
2847 /// [`clone`]: Clone::clone
2854 /// let a = [1, 2, 3];
2856 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2858 /// // cloned is the same as .map(|&x| x), for integers
2859 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2861 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2862 /// assert_eq!(v_map, vec![1, 2, 3]);
2864 #[stable(feature = "rust1", since = "1.0.0")]
2865 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2867 Self: Sized + Iterator<Item = &'a T>,
2873 /// Repeats an iterator endlessly.
2875 /// Instead of stopping at [`None`], the iterator will instead start again,
2876 /// from the beginning. After iterating again, it will start at the
2877 /// beginning again. And again. And again. Forever.
2884 /// let a = [1, 2, 3];
2886 /// let mut it = a.iter().cycle();
2888 /// assert_eq!(it.next(), Some(&1));
2889 /// assert_eq!(it.next(), Some(&2));
2890 /// assert_eq!(it.next(), Some(&3));
2891 /// assert_eq!(it.next(), Some(&1));
2892 /// assert_eq!(it.next(), Some(&2));
2893 /// assert_eq!(it.next(), Some(&3));
2894 /// assert_eq!(it.next(), Some(&1));
2896 #[stable(feature = "rust1", since = "1.0.0")]
2898 fn cycle(self) -> Cycle<Self>
2900 Self: Sized + Clone,
2905 /// Sums the elements of an iterator.
2907 /// Takes each element, adds them together, and returns the result.
2909 /// An empty iterator returns the zero value of the type.
2913 /// When calling `sum()` and a primitive integer type is being returned, this
2914 /// method will panic if the computation overflows and debug assertions are
2922 /// let a = [1, 2, 3];
2923 /// let sum: i32 = a.iter().sum();
2925 /// assert_eq!(sum, 6);
2927 #[stable(feature = "iter_arith", since = "1.11.0")]
2928 fn sum<S>(self) -> S
2936 /// Iterates over the entire iterator, multiplying all the elements
2938 /// An empty iterator returns the one value of the type.
2942 /// When calling `product()` and a primitive integer type is being returned,
2943 /// method will panic if the computation overflows and debug assertions are
2949 /// fn factorial(n: u32) -> u32 {
2950 /// (1..=n).product()
2952 /// assert_eq!(factorial(0), 1);
2953 /// assert_eq!(factorial(1), 1);
2954 /// assert_eq!(factorial(5), 120);
2956 #[stable(feature = "iter_arith", since = "1.11.0")]
2957 fn product<P>(self) -> P
2960 P: Product<Self::Item>,
2962 Product::product(self)
2965 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
2971 /// use std::cmp::Ordering;
2973 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
2974 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
2975 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
2977 #[stable(feature = "iter_order", since = "1.5.0")]
2978 fn cmp<I>(self, other: I) -> Ordering
2980 I: IntoIterator<Item = Self::Item>,
2984 self.cmp_by(other, |x, y| x.cmp(&y))
2987 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
2988 /// of another with respect to the specified comparison function.
2995 /// #![feature(iter_order_by)]
2997 /// use std::cmp::Ordering;
2999 /// let xs = [1, 2, 3, 4];
3000 /// let ys = [1, 4, 9, 16];
3002 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less);
3003 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal);
3004 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater);
3006 #[unstable(feature = "iter_order_by", issue = "64295")]
3007 fn cmp_by<I, F>(mut self, other: I, mut cmp: F) -> Ordering
3011 F: FnMut(Self::Item, I::Item) -> Ordering,
3013 let mut other = other.into_iter();
3016 let x = match self.next() {
3018 if other.next().is_none() {
3019 return Ordering::Equal;
3021 return Ordering::Less;
3027 let y = match other.next() {
3028 None => return Ordering::Greater,
3033 Ordering::Equal => (),
3034 non_eq => return non_eq,
3039 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3045 /// use std::cmp::Ordering;
3047 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
3048 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
3049 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
3051 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
3053 #[stable(feature = "iter_order", since = "1.5.0")]
3054 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
3057 Self::Item: PartialOrd<I::Item>,
3060 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
3063 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3064 /// of another with respect to the specified comparison function.
3071 /// #![feature(iter_order_by)]
3073 /// use std::cmp::Ordering;
3075 /// let xs = [1.0, 2.0, 3.0, 4.0];
3076 /// let ys = [1.0, 4.0, 9.0, 16.0];
3079 /// xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)),
3080 /// Some(Ordering::Less)
3083 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)),
3084 /// Some(Ordering::Equal)
3087 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)),
3088 /// Some(Ordering::Greater)
3091 #[unstable(feature = "iter_order_by", issue = "64295")]
3092 fn partial_cmp_by<I, F>(mut self, other: I, mut partial_cmp: F) -> Option<Ordering>
3096 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3098 let mut other = other.into_iter();
3101 let x = match self.next() {
3103 if other.next().is_none() {
3104 return Some(Ordering::Equal);
3106 return Some(Ordering::Less);
3112 let y = match other.next() {
3113 None => return Some(Ordering::Greater),
3117 match partial_cmp(x, y) {
3118 Some(Ordering::Equal) => (),
3119 non_eq => return non_eq,
3124 /// Determines if the elements of this [`Iterator`] are equal to those of
3130 /// assert_eq!([1].iter().eq([1].iter()), true);
3131 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3133 #[stable(feature = "iter_order", since = "1.5.0")]
3134 fn eq<I>(self, other: I) -> bool
3137 Self::Item: PartialEq<I::Item>,
3140 self.eq_by(other, |x, y| x == y)
3143 /// Determines if the elements of this [`Iterator`] are equal to those of
3144 /// another with respect to the specified equality function.
3151 /// #![feature(iter_order_by)]
3153 /// let xs = [1, 2, 3, 4];
3154 /// let ys = [1, 4, 9, 16];
3156 /// assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y));
3158 #[unstable(feature = "iter_order_by", issue = "64295")]
3159 fn eq_by<I, F>(mut self, other: I, mut eq: F) -> bool
3163 F: FnMut(Self::Item, I::Item) -> bool,
3165 let mut other = other.into_iter();
3168 let x = match self.next() {
3169 None => return other.next().is_none(),
3173 let y = match other.next() {
3174 None => return false,
3184 /// Determines if the elements of this [`Iterator`] are unequal to those of
3190 /// assert_eq!([1].iter().ne([1].iter()), false);
3191 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3193 #[stable(feature = "iter_order", since = "1.5.0")]
3194 fn ne<I>(self, other: I) -> bool
3197 Self::Item: PartialEq<I::Item>,
3203 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3204 /// less than those of another.
3209 /// assert_eq!([1].iter().lt([1].iter()), false);
3210 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3211 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3212 /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
3214 #[stable(feature = "iter_order", since = "1.5.0")]
3215 fn lt<I>(self, other: I) -> bool
3218 Self::Item: PartialOrd<I::Item>,
3221 self.partial_cmp(other) == Some(Ordering::Less)
3224 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3225 /// less or equal to those of another.
3230 /// assert_eq!([1].iter().le([1].iter()), true);
3231 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3232 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3233 /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
3235 #[stable(feature = "iter_order", since = "1.5.0")]
3236 fn le<I>(self, other: I) -> bool
3239 Self::Item: PartialOrd<I::Item>,
3242 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
3245 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3246 /// greater than those of another.
3251 /// assert_eq!([1].iter().gt([1].iter()), false);
3252 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3253 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3254 /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
3256 #[stable(feature = "iter_order", since = "1.5.0")]
3257 fn gt<I>(self, other: I) -> bool
3260 Self::Item: PartialOrd<I::Item>,
3263 self.partial_cmp(other) == Some(Ordering::Greater)
3266 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3267 /// greater than or equal to those of another.
3272 /// assert_eq!([1].iter().ge([1].iter()), true);
3273 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
3274 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
3275 /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
3277 #[stable(feature = "iter_order", since = "1.5.0")]
3278 fn ge<I>(self, other: I) -> bool
3281 Self::Item: PartialOrd<I::Item>,
3284 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
3287 /// Checks if the elements of this iterator are sorted.
3289 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3290 /// iterator yields exactly zero or one element, `true` is returned.
3292 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3293 /// implies that this function returns `false` if any two consecutive items are not
3299 /// #![feature(is_sorted)]
3301 /// assert!([1, 2, 2, 9].iter().is_sorted());
3302 /// assert!(![1, 3, 2, 4].iter().is_sorted());
3303 /// assert!([0].iter().is_sorted());
3304 /// assert!(std::iter::empty::<i32>().is_sorted());
3305 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
3308 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3309 fn is_sorted(self) -> bool
3312 Self::Item: PartialOrd,
3314 self.is_sorted_by(PartialOrd::partial_cmp)
3317 /// Checks if the elements of this iterator are sorted using the given comparator function.
3319 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3320 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3321 /// [`is_sorted`]; see its documentation for more information.
3326 /// #![feature(is_sorted)]
3328 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3329 /// assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3330 /// assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3331 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b)));
3332 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3335 /// [`is_sorted`]: Iterator::is_sorted
3336 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3337 fn is_sorted_by<F>(mut self, compare: F) -> bool
3340 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3345 mut compare: impl FnMut(&T, &T) -> Option<Ordering> + 'a,
3346 ) -> impl FnMut(T) -> bool + 'a {
3348 if let Some(Ordering::Greater) | None = compare(&last, &curr) {
3356 let mut last = match self.next() {
3358 None => return true,
3361 self.all(check(&mut last, compare))
3364 /// Checks if the elements of this iterator are sorted using the given key extraction
3367 /// Instead of comparing the iterator's elements directly, this function compares the keys of
3368 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
3369 /// its documentation for more information.
3371 /// [`is_sorted`]: Iterator::is_sorted
3376 /// #![feature(is_sorted)]
3378 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
3379 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
3382 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3383 fn is_sorted_by_key<F, K>(self, f: F) -> bool
3386 F: FnMut(Self::Item) -> K,
3389 self.map(f).is_sorted()
3392 /// See [TrustedRandomAccess]
3393 // The unusual name is to avoid name collisions in method resolution
3397 #[unstable(feature = "trusted_random_access", issue = "none")]
3398 unsafe fn __iterator_get_unchecked(&mut self, _idx: usize) -> Self::Item
3400 Self: TrustedRandomAccess,
3402 unreachable!("Always specialized");
3406 #[stable(feature = "rust1", since = "1.0.0")]
3407 impl<I: Iterator + ?Sized> Iterator for &mut I {
3408 type Item = I::Item;
3409 fn next(&mut self) -> Option<I::Item> {
3412 fn size_hint(&self) -> (usize, Option<usize>) {
3413 (**self).size_hint()
3415 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
3416 (**self).advance_by(n)
3418 fn nth(&mut self, n: usize) -> Option<Self::Item> {