pub trait Iterator { typeItem;Show 76 methods
// Required method fnnext(&mut self) ->Option<Self::Item>; // Provided methods fnnext_chunk<const N:usize>( &mut self, ) ->Result<[Self::Item;N],IntoIter<Self::Item, N>>where Self:Sized { ... } fnsize_hint(&self) -> (usize,Option<usize>) { ... } fncount(self) ->usizewhere Self:Sized { ... } fnlast(self) ->Option<Self::Item>where Self:Sized { ... } fnadvance_by(&mut self, n:usize) ->Result<(),NonZero<usize>> { ... } fnnth(&mut self, n:usize) ->Option<Self::Item> { ... } fnstep_by(self, step:usize) ->StepBy<Self>ⓘwhere Self:Sized { ... } fnchain<U>(self, other: U) ->Chain<Self, <U asIntoIterator>::IntoIter>ⓘwhere Self:Sized, U:IntoIterator<Item = Self::Item> { ... } fnzip<U>(self, other: U) ->Zip<Self, <U asIntoIterator>::IntoIter>ⓘwhere Self:Sized, U:IntoIterator { ... } fnintersperse(self, separator: Self::Item) ->Intersperse<Self>ⓘwhere Self:Sized, Self::Item:Clone { ... } fnintersperse_with<G>(self, separator: G) ->IntersperseWith<Self, G>ⓘwhere Self:Sized, G:FnMut() -> Self::Item { ... } fnmap<B, F>(self, f: F) ->Map<Self, F>ⓘwhere Self:Sized, F:FnMut(Self::Item) -> B { ... } fnfor_each<F>(self, f: F)where Self:Sized, F:FnMut(Self::Item) { ... } fnfilter<P>(self, predicate: P) ->Filter<Self, P>ⓘwhere Self:Sized, P:FnMut(&Self::Item) ->bool { ... } fnfilter_map<B, F>(self, f: F) ->FilterMap<Self, F>ⓘwhere Self:Sized, F:FnMut(Self::Item) ->Option<B> { ... } fnenumerate(self) ->Enumerate<Self>ⓘwhere Self:Sized { ... } fnpeekable(self) ->Peekable<Self>ⓘwhere Self:Sized { ... } fnskip_while<P>(self, predicate: P) ->SkipWhile<Self, P>ⓘwhere Self:Sized, P:FnMut(&Self::Item) ->bool { ... } fntake_while<P>(self, predicate: P) ->TakeWhile<Self, P>ⓘwhere Self:Sized, P:FnMut(&Self::Item) ->bool { ... } fnmap_while<B, P>(self, predicate: P) ->MapWhile<Self, P>ⓘwhere Self:Sized, P:FnMut(Self::Item) ->Option<B> { ... } fnskip(self, n:usize) ->Skip<Self>ⓘwhere Self:Sized { ... } fntake(self, n:usize) ->Take<Self>ⓘwhere Self:Sized { ... } fnscan<St, B, F>(self, initial_state: St, f: F) ->Scan<Self, St, F>ⓘwhere Self:Sized, F:FnMut(&mut St, Self::Item) ->Option<B> { ... } fnflat_map<U, F>(self, f: F) ->FlatMap<Self, U, F>ⓘwhere Self:Sized, U:IntoIterator, F:FnMut(Self::Item) -> U { ... } fnflatten(self) ->Flatten<Self>ⓘwhere Self:Sized, Self::Item:IntoIterator { ... } fnmap_windows<F, R, const N:usize>(self, f: F) ->MapWindows<Self, F, N>ⓘwhere Self:Sized, F:FnMut(&[Self::Item;N]) -> R { ... } fnfuse(self) ->Fuse<Self>ⓘwhere Self:Sized { ... } fninspect<F>(self, f: F) ->Inspect<Self, F>ⓘwhere Self:Sized, F:FnMut(&Self::Item) { ... } fnby_ref(&mut self) -> &mut Selfwhere Self:Sized { ... } fncollect<B>(self) -> Bwhere B:FromIterator<Self::Item>, Self:Sized { ... } fntry_collect<B>( &mut self, ) -> <<Self::Item asTry>::Residual asResidual<B>>::TryTypewhere Self:Sized, Self::Item:Try, <Self::Item asTry>::Residual:Residual<B>, B:FromIterator<<Self::Item asTry>::Output> { ... } fncollect_into<E>(self, collection:&mut E) ->&mut Ewhere E:Extend<Self::Item>, Self:Sized { ... } fnpartition<B, F>(self, f: F) ->(B, B)where Self:Sized, B:Default +Extend<Self::Item>, F:FnMut(&Self::Item) ->bool { ... } fnpartition_in_place<'a, T, P>(self, predicate: P) ->usizewhere T: 'a, Self:Sized +DoubleEndedIterator<Item =&'a mut T>, P:FnMut(&T) ->bool { ... } fnis_partitioned<P>(self, predicate: P) ->boolwhere Self:Sized, P:FnMut(Self::Item) ->bool { ... } fntry_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere Self:Sized, F:FnMut(B, Self::Item) -> R, R:Try<Output = B> { ... } fntry_for_each<F, R>(&mut self, f: F) -> Rwhere Self:Sized, F:FnMut(Self::Item) -> R, R:Try<Output =()> { ... } fnfold<B, F>(self, init: B, f: F) -> Bwhere Self:Sized, F:FnMut(B, Self::Item) -> B { ... } fnreduce<F>(self, f: F) ->Option<Self::Item>where Self:Sized, F:FnMut(Self::Item, Self::Item) -> Self::Item { ... } fntry_reduce<R>( &mut self, f: implFnMut(Self::Item, Self::Item) -> R, ) -> <<R asTry>::Residual asResidual<Option<<R asTry>::Output>>>::TryTypewhere Self:Sized, R:Try<Output = Self::Item>, <R asTry>::Residual:Residual<Option<Self::Item>> { ... } fnall<F>(&mut self, f: F) ->boolwhere Self:Sized, F:FnMut(Self::Item) ->bool { ... } fnany<F>(&mut self, f: F) ->boolwhere Self:Sized, F:FnMut(Self::Item) ->bool { ... } fnfind<P>(&mut self, predicate: P) ->Option<Self::Item>where Self:Sized, P:FnMut(&Self::Item) ->bool { ... } fnfind_map<B, F>(&mut self, f: F) ->Option<B>where Self:Sized, F:FnMut(Self::Item) ->Option<B> { ... } fntry_find<R>( &mut self, f: implFnMut(&Self::Item) -> R, ) -> <<R asTry>::Residual asResidual<Option<Self::Item>>>::TryTypewhere Self:Sized, R:Try<Output =bool>, <R asTry>::Residual:Residual<Option<Self::Item>> { ... } fnposition<P>(&mut self, predicate: P) ->Option<usize>where Self:Sized, P:FnMut(Self::Item) ->bool { ... } fnrposition<P>(&mut self, predicate: P) ->Option<usize>where P:FnMut(Self::Item) ->bool, Self:Sized +ExactSizeIterator +DoubleEndedIterator { ... } fnmax(self) ->Option<Self::Item>where Self:Sized, Self::Item:Ord { ... } fnmin(self) ->Option<Self::Item>where Self:Sized, Self::Item:Ord { ... } fnmax_by_key<B, F>(self, f: F) ->Option<Self::Item>where B:Ord, Self:Sized, F:FnMut(&Self::Item) -> B { ... } fnmax_by<F>(self, compare: F) ->Option<Self::Item>where Self:Sized, F:FnMut(&Self::Item, &Self::Item) ->Ordering { ... } fnmin_by_key<B, F>(self, f: F) ->Option<Self::Item>where B:Ord, Self:Sized, F:FnMut(&Self::Item) -> B { ... } fnmin_by<F>(self, compare: F) ->Option<Self::Item>where Self:Sized, F:FnMut(&Self::Item, &Self::Item) ->Ordering { ... } fnrev(self) ->Rev<Self>ⓘwhere Self:Sized +DoubleEndedIterator { ... } fnunzip<A, B, FromA, FromB>(self) ->(FromA, FromB)where FromA:Default +Extend<A>, FromB:Default +Extend<B>, Self:Sized +Iterator<Item =(A, B)> { ... } fncopied<'a, T>(self) ->Copied<Self>ⓘwhere T:Copy + 'a, Self:Sized +Iterator<Item =&'a T> { ... } fncloned<'a, T>(self) ->Cloned<Self>ⓘwhere T:Clone + 'a, Self:Sized +Iterator<Item =&'a T> { ... } fncycle(self) ->Cycle<Self>ⓘwhere Self:Sized +Clone { ... } fnarray_chunks<const N:usize>(self) ->ArrayChunks<Self, N>ⓘwhere Self:Sized { ... } fnsum<S>(self) -> Swhere Self:Sized, S:Sum<Self::Item> { ... } fnproduct<P>(self) -> Pwhere Self:Sized, P:Product<Self::Item> { ... } fncmp<I>(self, other: I) ->Orderingwhere I:IntoIterator<Item = Self::Item>, Self::Item:Ord, Self:Sized { ... } fncmp_by<I, F>(self, other: I, cmp: F) ->Orderingwhere Self:Sized, I:IntoIterator, F:FnMut(Self::Item, <I asIntoIterator>::Item) ->Ordering { ... } fnpartial_cmp<I>(self, other: I) ->Option<Ordering>where I:IntoIterator, Self::Item:PartialOrd<<I asIntoIterator>::Item>, Self:Sized { ... } fnpartial_cmp_by<I, F>(self, other: I, partial_cmp: F) ->Option<Ordering>where Self:Sized, I:IntoIterator, F:FnMut(Self::Item, <I asIntoIterator>::Item) ->Option<Ordering> { ... } fneq<I>(self, other: I) ->boolwhere I:IntoIterator, Self::Item:PartialEq<<I asIntoIterator>::Item>, Self:Sized { ... } fneq_by<I, F>(self, other: I, eq: F) ->boolwhere Self:Sized, I:IntoIterator, F:FnMut(Self::Item, <I asIntoIterator>::Item) ->bool { ... } fnne<I>(self, other: I) ->boolwhere I:IntoIterator, Self::Item:PartialEq<<I asIntoIterator>::Item>, Self:Sized { ... } fnlt<I>(self, other: I) ->boolwhere I:IntoIterator, Self::Item:PartialOrd<<I asIntoIterator>::Item>, Self:Sized { ... } fnle<I>(self, other: I) ->boolwhere I:IntoIterator, Self::Item:PartialOrd<<I asIntoIterator>::Item>, Self:Sized { ... } fngt<I>(self, other: I) ->boolwhere I:IntoIterator, Self::Item:PartialOrd<<I asIntoIterator>::Item>, Self:Sized { ... } fnge<I>(self, other: I) ->boolwhere I:IntoIterator, Self::Item:PartialOrd<<I asIntoIterator>::Item>, Self:Sized { ... } fnis_sorted(self) ->boolwhere Self:Sized, Self::Item:PartialOrd { ... } fnis_sorted_by<F>(self, compare: F) ->boolwhere Self:Sized, F:FnMut(&Self::Item, &Self::Item) ->bool { ... } fnis_sorted_by_key<F, K>(self, f: F) ->boolwhere Self:Sized, F:FnMut(Self::Item) -> K, K:PartialOrd { ... }}Expand description
A trait for dealing with iterators.
This is the main iterator trait. For more about the concept of iteratorsgenerally, please see themodule-level documentation. In particular, youmay want to know how toimplementIterator.
Required Associated Types§
Required Methods§
1.0.0 ·Sourcefnnext(&mut self) ->Option<Self::Item>
fnnext(&mut self) ->Option<Self::Item>
Advances the iterator and returns the next value.
ReturnsNone when iteration is finished. Individual iteratorimplementations may choose to resume iteration, and so callingnext()again may or may not eventually start returningSome(Item) again at somepoint.
§Examples
leta = [1,2,3];letmutiter = a.into_iter();// A call to next() returns the next value...assert_eq!(Some(1), iter.next());assert_eq!(Some(2), iter.next());assert_eq!(Some(3), iter.next());// ... and then None once it's over.assert_eq!(None, iter.next());// More calls may or may not return `None`. Here, they always will.assert_eq!(None, iter.next());assert_eq!(None, iter.next());Provided Methods§
Sourcefnnext_chunk<const N:usize>( &mut self,) ->Result<[Self::Item;N],IntoIter<Self::Item, N>>where Self:Sized,
🔬This is a nightly-only experimental API. (iter_next_chunk #98326)
fnnext_chunk<const N:usize>( &mut self,) ->Result<[Self::Item;N],IntoIter<Self::Item, N>>where Self:Sized,
iter_next_chunk #98326)Advances the iterator and returns an array containing the nextN values.
If there are not enough elements to fill the array thenErr is returnedcontaining an iterator over the remaining elements.
§Examples
Basic usage:
#![feature(iter_next_chunk)]letmutiter ="lorem".chars();assert_eq!(iter.next_chunk().unwrap(), ['l','o']);// N is inferred as 2assert_eq!(iter.next_chunk().unwrap(), ['r','e','m']);// N is inferred as 3assert_eq!(iter.next_chunk::<4>().unwrap_err().as_slice(),&[]);// N is explicitly 4Split a string and get the first three items.
1.0.0 ·Sourcefnsize_hint(&self) -> (usize,Option<usize>)
fnsize_hint(&self) -> (usize,Option<usize>)
Returns the bounds on the remaining length of the iterator.
Specifically,size_hint() returns a tuple where the first elementis the lower bound, and the second element is the upper bound.
The second half of the tuple that is returned is anOption<usize>.ANone here means that either there is no known upper bound, or theupper bound is larger thanusize.
§Implementation notes
It is not enforced that an iterator implementation yields the declarednumber of elements. A buggy iterator may yield less than the lower boundor more than the upper bound of elements.
size_hint() is primarily intended to be used for optimizations such asreserving space for the elements of the iterator, but must not betrusted to e.g., omit bounds checks in unsafe code. An incorrectimplementation ofsize_hint() should not lead to memory safetyviolations.
That said, the implementation should provide a correct estimation,because otherwise it would be a violation of the trait’s protocol.
The default implementation returns(0,None) which is correct for anyiterator.
§Examples
Basic usage:
leta = [1,2,3];letmutiter = a.iter();assert_eq!((3,Some(3)), iter.size_hint());let _= iter.next();assert_eq!((2,Some(2)), iter.size_hint());A more complex example:
// The even numbers in the range of zero to nine.letiter = (0..10).filter(|x| x %2==0);// We might iterate from zero to ten times. Knowing that it's five// exactly wouldn't be possible without executing filter().assert_eq!((0,Some(10)), iter.size_hint());// Let's add five more numbers with chain()letiter = (0..10).filter(|x| x %2==0).chain(15..20);// now both bounds are increased by fiveassert_eq!((5,Some(15)), iter.size_hint());ReturningNone for an upper bound:
1.0.0 ·Sourcefncount(self) ->usizewhere Self:Sized,
fncount(self) ->usizewhere Self:Sized,
Consumes the iterator, counting the number of iterations and returning it.
This method will callnext repeatedly untilNone is encountered,returning the number of times it sawSome. Note thatnext has to becalled at least once even if the iterator does not have any elements.
§Overflow Behavior
The method does no guarding against overflows, so counting elements ofan iterator with more thanusize::MAX elements either produces thewrong result or panics. If overflow checks are enabled, a panic isguaranteed.
§Panics
This function might panic if the iterator has more thanusize::MAXelements.
§Examples
1.0.0 ·Sourcefnlast(self) ->Option<Self::Item>where Self:Sized,
fnlast(self) ->Option<Self::Item>where Self:Sized,
Sourcefnadvance_by(&mut self, n:usize) ->Result<(),NonZero<usize>>
🔬This is a nightly-only experimental API. (iter_advance_by #77404)
fnadvance_by(&mut self, n:usize) ->Result<(),NonZero<usize>>
iter_advance_by #77404)Advances the iterator byn elements.
This method will eagerly skipn elements by callingnext up tontimes untilNone is encountered.
advance_by(n) will returnOk(()) if the iterator successfully advances byn elements, or aErr(NonZero<usize>) with valuek ifNone is encountered,wherek is remaining number of steps that could not be advanced because the iterator ran out.Ifself is empty andn is non-zero, then this returnsErr(n).Otherwise,k is always less thann.
Callingadvance_by(0) can do meaningful work, for exampleFlattencan advance its outer iterator until it finds an inner iterator that is not empty, whichthen often allows it to return a more accuratesize_hint() than in its initial state.
§Examples
1.0.0 ·Sourcefnnth(&mut self, n:usize) ->Option<Self::Item>
fnnth(&mut self, n:usize) ->Option<Self::Item>
Returns thenth element of the iterator.
Like most indexing operations, the count starts from zero, sonth(0)returns the first value,nth(1) the second, and so on.
Note that all preceding elements, as well as the returned element, will beconsumed from the iterator. That means that the preceding elements will bediscarded, and also that callingnth(0) multiple times on the same iteratorwill return different elements.
nth() will returnNone ifn is greater than or equal to the length of theiterator.
§Examples
Basic usage:
Callingnth() multiple times doesn’t rewind the iterator:
leta = [1,2,3];letmutiter = a.into_iter();assert_eq!(iter.nth(1),Some(2));assert_eq!(iter.nth(1),None);ReturningNone if there are less thann + 1 elements:
1.28.0 ·Sourcefnstep_by(self, step:usize) ->StepBy<Self>ⓘwhere Self:Sized,
fnstep_by(self, step:usize) ->StepBy<Self>ⓘwhere Self:Sized,
Creates an iterator starting at the same point, but stepping bythe given amount at each iteration.
Note 1: The first element of the iterator will always be returned,regardless of the step given.
Note 2: The time at which ignored elements are pulled is not fixed.StepBy behaves like the sequenceself.next(),self.nth(step-1),self.nth(step-1), …, but is also free to behave like the sequenceadvance_n_and_return_first(&mut self, step),advance_n_and_return_first(&mut self, step), …Which way is used may change for some iterators for performance reasons.The second way will advance the iterator earlier and may consume more items.
advance_n_and_return_first is the equivalent of:
fnadvance_n_and_return_first<I>(iter:&mutI, n: usize) ->Option<I::Item>whereI: Iterator,{letnext = iter.next();ifn >1{ iter.nth(n -2); } next}§Panics
The method will panic if the given step is0.
§Examples
1.0.0 ·Sourcefnchain<U>(self, other: U) ->Chain<Self, <U asIntoIterator>::IntoIter>ⓘ
fnchain<U>(self, other: U) ->Chain<Self, <U asIntoIterator>::IntoIter>ⓘ
Takes two iterators and creates a new iterator over both in sequence.
chain() will return a new iterator which will first iterate overvalues from the first iterator and then over values from the seconditerator.
In other words, it links two iterators together, in a chain. 🔗
once is commonly used to adapt a single value into a chain ofother kinds of iteration.
§Examples
Basic usage:
lets1 ="abc".chars();lets2 ="def".chars();letmutiter = s1.chain(s2);assert_eq!(iter.next(),Some('a'));assert_eq!(iter.next(),Some('b'));assert_eq!(iter.next(),Some('c'));assert_eq!(iter.next(),Some('d'));assert_eq!(iter.next(),Some('e'));assert_eq!(iter.next(),Some('f'));assert_eq!(iter.next(),None);Since the argument tochain() usesIntoIterator, we can passanything that can be converted into anIterator, not just anIterator itself. For example, arrays ([T]) implementIntoIterator, and so can be passed tochain() directly:
leta1 = [1,2,3];leta2 = [4,5,6];letmutiter = a1.into_iter().chain(a2);assert_eq!(iter.next(),Some(1));assert_eq!(iter.next(),Some(2));assert_eq!(iter.next(),Some(3));assert_eq!(iter.next(),Some(4));assert_eq!(iter.next(),Some(5));assert_eq!(iter.next(),Some(6));assert_eq!(iter.next(),None);If you work with Windows API, you may wish to convertOsStr toVec<u16>:
1.0.0 ·Sourcefnzip<U>(self, other: U) ->Zip<Self, <U asIntoIterator>::IntoIter>ⓘwhere Self:Sized, U:IntoIterator,
fnzip<U>(self, other: U) ->Zip<Self, <U asIntoIterator>::IntoIter>ⓘwhere Self:Sized, U:IntoIterator,
‘Zips up’ two iterators into a single iterator of pairs.
zip() returns a new iterator that will iterate over two otheriterators, returning a tuple where the first element comes from thefirst iterator, and the second element comes from the second iterator.
In other words, it zips two iterators together, into a single one.
If either iterator returnsNone,next from the zipped iteratorwill returnNone.If the zipped iterator has no more elements to return then each further attempt to advanceit will first try to advance the first iterator at most one time and if it still yielded an itemtry to advance the second iterator at most one time.
To ‘undo’ the result of zipping up two iterators, seeunzip.
§Examples
Basic usage:
lets1 ="abc".chars();lets2 ="def".chars();letmutiter = s1.zip(s2);assert_eq!(iter.next(),Some(('a','d')));assert_eq!(iter.next(),Some(('b','e')));assert_eq!(iter.next(),Some(('c','f')));assert_eq!(iter.next(),None);Since the argument tozip() usesIntoIterator, we can passanything that can be converted into anIterator, not just anIterator itself. For example, arrays ([T]) implementIntoIterator, and so can be passed tozip() directly:
leta1 = [1,2,3];leta2 = [4,5,6];letmutiter = a1.into_iter().zip(a2);assert_eq!(iter.next(),Some((1,4)));assert_eq!(iter.next(),Some((2,5)));assert_eq!(iter.next(),Some((3,6)));assert_eq!(iter.next(),None);zip() is often used to zip an infinite iterator to a finite one.This works because the finite iterator will eventually returnNone,ending the zipper. Zipping with(0..) can look a lot likeenumerate:
letenumerate: Vec<_> ="foo".chars().enumerate().collect();letzipper: Vec<_> = (0..).zip("foo".chars()).collect();assert_eq!((0,'f'), enumerate[0]);assert_eq!((0,'f'), zipper[0]);assert_eq!((1,'o'), enumerate[1]);assert_eq!((1,'o'), zipper[1]);assert_eq!((2,'o'), enumerate[2]);assert_eq!((2,'o'), zipper[2]);If both iterators have roughly equivalent syntax, it may be more readable to usezip:
usestd::iter::zip;leta = [1,2,3];letb = [2,3,4];letmutzipped = zip( a.into_iter().map(|x| x *2).skip(1), b.into_iter().map(|x| x *2).skip(1),);assert_eq!(zipped.next(),Some((4,6)));assert_eq!(zipped.next(),Some((6,8)));assert_eq!(zipped.next(),None);compared to:
Sourcefnintersperse(self, separator: Self::Item) ->Intersperse<Self>ⓘ
🔬This is a nightly-only experimental API. (iter_intersperse #79524)
fnintersperse(self, separator: Self::Item) ->Intersperse<Self>ⓘ
iter_intersperse #79524)Creates a new iterator which places a copy ofseparator between adjacentitems of the original iterator.
In caseseparator does not implementClone or needs to becomputed every time, useintersperse_with.
§Examples
Basic usage:
#![feature(iter_intersperse)]letmuta = [0,1,2].into_iter().intersperse(100);assert_eq!(a.next(),Some(0));// The first element from `a`.assert_eq!(a.next(),Some(100));// The separator.assert_eq!(a.next(),Some(1));// The next element from `a`.assert_eq!(a.next(),Some(100));// The separator.assert_eq!(a.next(),Some(2));// The last element from `a`.assert_eq!(a.next(),None);// The iterator is finished.intersperse can be very useful to join an iterator’s items using a common element:
Sourcefnintersperse_with<G>(self, separator: G) ->IntersperseWith<Self, G>ⓘ
🔬This is a nightly-only experimental API. (iter_intersperse #79524)
fnintersperse_with<G>(self, separator: G) ->IntersperseWith<Self, G>ⓘ
iter_intersperse #79524)Creates a new iterator which places an item generated byseparatorbetween adjacent items of the original iterator.
The closure will be called exactly once each time an item is placedbetween two adjacent items from the underlying iterator; specifically,the closure is not called if the underlying iterator yields less thantwo items and after the last item is yielded.
If the iterator’s item implementsClone, it may be easier to useintersperse.
§Examples
Basic usage:
#![feature(iter_intersperse)]#[derive(PartialEq, Debug)]structNotClone(usize);letv = [NotClone(0), NotClone(1), NotClone(2)];letmutit = v.into_iter().intersperse_with(|| NotClone(99));assert_eq!(it.next(),Some(NotClone(0)));// The first element from `v`.assert_eq!(it.next(),Some(NotClone(99)));// The separator.assert_eq!(it.next(),Some(NotClone(1)));// The next element from `v`.assert_eq!(it.next(),Some(NotClone(99)));// The separator.assert_eq!(it.next(),Some(NotClone(2)));// The last element from `v`.assert_eq!(it.next(),None);// The iterator is finished.intersperse_with can be used in situations where the separator needsto be computed:
#![feature(iter_intersperse)]letsrc = ["Hello","to","all","people","!!"].iter().copied();// The closure mutably borrows its context to generate an item.letmuthappy_emojis = [" ❤️ "," 😀 "].into_iter();letseparator = || happy_emojis.next().unwrap_or(" 🦀 ");letresult = src.intersperse_with(separator).collect::<String>();assert_eq!(result,"Hello ❤️ to 😀 all 🦀 people 🦀 !!");1.0.0 ·Sourcefnmap<B, F>(self, f: F) ->Map<Self, F>ⓘ
fnmap<B, F>(self, f: F) ->Map<Self, F>ⓘ
Takes a closure and creates an iterator which calls that closure on eachelement.
map() transforms one iterator into another, by means of its argument:something that implementsFnMut. It produces a new iterator whichcalls this closure on each element of the original iterator.
If you are good at thinking in types, you can think ofmap() like this:If you have an iterator that gives you elements of some typeA, andyou want an iterator of some other typeB, you can usemap(),passing a closure that takes anA and returns aB.
map() is conceptually similar to afor loop. However, asmap() islazy, it is best used when you’re already working with other iterators.If you’re doing some sort of looping for a side effect, it’s consideredmore idiomatic to usefor thanmap().
§Examples
Basic usage:
leta = [1,2,3];letmutiter = a.iter().map(|x|2* x);assert_eq!(iter.next(),Some(2));assert_eq!(iter.next(),Some(4));assert_eq!(iter.next(),Some(6));assert_eq!(iter.next(),None);If you’re doing some sort of side effect, preferfor tomap():
1.21.0 ·Sourcefnfor_each<F>(self, f: F)
fnfor_each<F>(self, f: F)
Calls a closure on each element of an iterator.
This is equivalent to using afor loop on the iterator, althoughbreak andcontinue are not possible from a closure. It’s generallymore idiomatic to use afor loop, butfor_each may be more legiblewhen processing items at the end of longer iterator chains. In somecasesfor_each may also be faster than a loop, because it will useinternal iteration on adapters likeChain.
§Examples
Basic usage:
usestd::sync::mpsc::channel;let(tx, rx) = channel();(0..5).map(|x| x *2+1) .for_each(move|x| tx.send(x).unwrap());letv: Vec<_> = rx.iter().collect();assert_eq!(v,vec![1,3,5,7,9]);For such a small example, afor loop may be cleaner, butfor_eachmight be preferable to keep a functional style with longer iterators:
1.0.0 ·Sourcefnfilter<P>(self, predicate: P) ->Filter<Self, P>ⓘ
fnfilter<P>(self, predicate: P) ->Filter<Self, P>ⓘ
Creates an iterator which uses a closure to determine if an elementshould be yielded.
Given an element the closure must returntrue orfalse. The returnediterator will yield only the elements for which the closure returnstrue.
§Examples
Basic usage:
leta = [0i32,1,2];letmutiter = a.into_iter().filter(|x| x.is_positive());assert_eq!(iter.next(),Some(1));assert_eq!(iter.next(),Some(2));assert_eq!(iter.next(),None);Because the closure passed tofilter() takes a reference, and manyiterators iterate over references, this leads to a possibly confusingsituation, where the type of the closure is a double reference:
lets =&[0,1,2];letmutiter = s.iter().filter(|x|**x >1);// needs two *s!assert_eq!(iter.next(),Some(&2));assert_eq!(iter.next(),None);It’s common to instead use destructuring on the argument to strip away one:
lets =&[0,1,2];letmutiter = s.iter().filter(|&x|*x >1);// both & and *assert_eq!(iter.next(),Some(&2));assert_eq!(iter.next(),None);or both:
lets =&[0,1,2];letmutiter = s.iter().filter(|&&x| x >1);// two &sassert_eq!(iter.next(),Some(&2));assert_eq!(iter.next(),None);of these layers.
Note thatiter.filter(f).next() is equivalent toiter.find(f).
1.0.0 ·Sourcefnfilter_map<B, F>(self, f: F) ->FilterMap<Self, F>ⓘ
fnfilter_map<B, F>(self, f: F) ->FilterMap<Self, F>ⓘ
Creates an iterator that both filters and maps.
The returned iterator yields only thevalues for which the suppliedclosure returnsSome(value).
filter_map can be used to make chains offilter andmap moreconcise. The example below shows how amap().filter().map() can beshortened to a single call tofilter_map.
§Examples
Basic usage:
1.0.0 ·Sourcefnenumerate(self) ->Enumerate<Self>ⓘwhere Self:Sized,
fnenumerate(self) ->Enumerate<Self>ⓘwhere Self:Sized,
Creates an iterator which gives the current iteration count as well asthe next value.
The iterator returned yields pairs(i, val), wherei is thecurrent index of iteration andval is the value returned by theiterator.
enumerate() keeps its count as ausize. If you want to count by adifferent sized integer, thezip function provides similarfunctionality.
§Overflow Behavior
The method does no guarding against overflows, so enumerating more thanusize::MAX elements either produces the wrong result or panics. Ifoverflow checks are enabled, a panic is guaranteed.
§Panics
The returned iterator might panic if the to-be-returned index wouldoverflow ausize.
§Examples
1.0.0 ·Sourcefnpeekable(self) ->Peekable<Self>ⓘwhere Self:Sized,
fnpeekable(self) ->Peekable<Self>ⓘwhere Self:Sized,
Creates an iterator which can use thepeek andpeek_mut methodsto look at the next element of the iterator without consuming it. Seetheir documentation for more information.
Note that the underlying iterator is still advanced whenpeek orpeek_mut are called for the first time: In order to retrieve thenext element,next is called on the underlying iterator, hence anyside effects (i.e. anything other than fetching the next value) ofthenext method will occur.
§Examples
Basic usage:
letxs = [1,2,3];letmutiter = xs.into_iter().peekable();// peek() lets us see into the futureassert_eq!(iter.peek(),Some(&1));assert_eq!(iter.next(),Some(1));assert_eq!(iter.next(),Some(2));// we can peek() multiple times, the iterator won't advanceassert_eq!(iter.peek(),Some(&3));assert_eq!(iter.peek(),Some(&3));assert_eq!(iter.next(),Some(3));// after the iterator is finished, so is peek()assert_eq!(iter.peek(),None);assert_eq!(iter.next(),None);Usingpeek_mut to mutate the next item without advancing theiterator:
letxs = [1,2,3];letmutiter = xs.into_iter().peekable();// `peek_mut()` lets us see into the futureassert_eq!(iter.peek_mut(),Some(&mut1));assert_eq!(iter.peek_mut(),Some(&mut1));assert_eq!(iter.next(),Some(1));if letSome(p) = iter.peek_mut() {assert_eq!(*p,2);// put a value into the iterator*p =1000;}// The value reappears as the iterator continuesassert_eq!(iter.collect::<Vec<_>>(),vec![1000,3]);1.0.0 ·Sourcefnskip_while<P>(self, predicate: P) ->SkipWhile<Self, P>ⓘ
fnskip_while<P>(self, predicate: P) ->SkipWhile<Self, P>ⓘ
Creates an iterator thatskips elements based on a predicate.
skip_while() takes a closure as an argument. It will call thisclosure on each element of the iterator, and ignore elementsuntil it returnsfalse.
Afterfalse is returned,skip_while()’s job is over, and therest of the elements are yielded.
§Examples
Basic usage:
leta = [-1i32,0,1];letmutiter = a.into_iter().skip_while(|x| x.is_negative());assert_eq!(iter.next(),Some(0));assert_eq!(iter.next(),Some(1));assert_eq!(iter.next(),None);Because the closure passed toskip_while() takes a reference, and manyiterators iterate over references, this leads to a possibly confusingsituation, where the type of the closure argument is a double reference:
lets =&[-1,0,1];letmutiter = s.iter().skip_while(|x|**x <0);// need two *s!assert_eq!(iter.next(),Some(&0));assert_eq!(iter.next(),Some(&1));assert_eq!(iter.next(),None);Stopping after an initialfalse:
1.0.0 ·Sourcefntake_while<P>(self, predicate: P) ->TakeWhile<Self, P>ⓘ
fntake_while<P>(self, predicate: P) ->TakeWhile<Self, P>ⓘ
Creates an iterator that yields elements based on a predicate.
take_while() takes a closure as an argument. It will call thisclosure on each element of the iterator, and yield elementswhile it returnstrue.
Afterfalse is returned,take_while()’s job is over, and therest of the elements are ignored.
§Examples
Basic usage:
leta = [-1i32,0,1];letmutiter = a.into_iter().take_while(|x| x.is_negative());assert_eq!(iter.next(),Some(-1));assert_eq!(iter.next(),None);Because the closure passed totake_while() takes a reference, and manyiterators iterate over references, this leads to a possibly confusingsituation, where the type of the closure is a double reference:
lets =&[-1,0,1];letmutiter = s.iter().take_while(|x|**x <0);// need two *s!assert_eq!(iter.next(),Some(&-1));assert_eq!(iter.next(),None);Stopping after an initialfalse:
leta = [-1,0,1, -2];letmutiter = a.into_iter().take_while(|&x| x <0);assert_eq!(iter.next(),Some(-1));// We have more elements that are less than zero, but since we already// got a false, take_while() ignores the remaining elements.assert_eq!(iter.next(),None);Becausetake_while() needs to look at the value in order to see if itshould be included or not, consuming iterators will see that it isremoved:
leta = [1,2,3,4];letmutiter = a.into_iter();letresult: Vec<i32> = iter.by_ref().take_while(|&n|n !=3).collect();assert_eq!(result, [1,2]);letresult: Vec<i32> = iter.collect();assert_eq!(result, [4]);The3 is no longer there, because it was consumed in order to see ifthe iteration should stop, but wasn’t placed back into the iterator.
1.57.0 ·Sourcefnmap_while<B, P>(self, predicate: P) ->MapWhile<Self, P>ⓘ
fnmap_while<B, P>(self, predicate: P) ->MapWhile<Self, P>ⓘ
Creates an iterator that both yields elements based on a predicate and maps.
map_while() takes a closure as an argument. It will call thisclosure on each element of the iterator, and yield elementswhile it returnsSome(_).
§Examples
Basic usage:
leta = [-1i32,4,0,1];letmutiter = a.into_iter().map_while(|x|16i32.checked_div(x));assert_eq!(iter.next(),Some(-16));assert_eq!(iter.next(),Some(4));assert_eq!(iter.next(),None);Here’s the same example, but withtake_while andmap:
leta = [-1i32,4,0,1];letmutiter = a.into_iter() .map(|x|16i32.checked_div(x)) .take_while(|x| x.is_some()) .map(|x| x.unwrap());assert_eq!(iter.next(),Some(-16));assert_eq!(iter.next(),Some(4));assert_eq!(iter.next(),None);Stopping after an initialNone:
leta = [0,1,2, -3,4,5, -6];letiter = a.into_iter().map_while(|x| u32::try_from(x).ok());letvec: Vec<_> = iter.collect();// We have more elements that could fit in u32 (such as 4, 5), but `map_while` returned `None` for `-3`// (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.assert_eq!(vec, [0,1,2]);Becausemap_while() needs to look at the value in order to see if itshould be included or not, consuming iterators will see that it isremoved:
leta = [1,2, -3,4];letmutiter = a.into_iter();letresult: Vec<u32> = iter.by_ref() .map_while(|n| u32::try_from(n).ok()) .collect();assert_eq!(result, [1,2]);letresult: Vec<i32> = iter.collect();assert_eq!(result, [4]);The-3 is no longer there, because it was consumed in order to see ifthe iteration should stop, but wasn’t placed back into the iterator.
Note that unliketake_while this iterator isnot fused.It is also not specified what this iterator returns after the firstNone is returned.If you need a fused iterator, usefuse.
1.0.0 ·Sourcefnskip(self, n:usize) ->Skip<Self>ⓘwhere Self:Sized,
fnskip(self, n:usize) ->Skip<Self>ⓘwhere Self:Sized,
Creates an iterator that skips the firstn elements.
skip(n) skips elements untiln elements are skipped or the end of theiterator is reached (whichever happens first). After that, all the remainingelements are yielded. In particular, if the original iterator is too short,then the returned iterator is empty.
Rather than overriding this method directly, instead override thenth method.
§Examples
1.0.0 ·Sourcefntake(self, n:usize) ->Take<Self>ⓘwhere Self:Sized,
fntake(self, n:usize) ->Take<Self>ⓘwhere Self:Sized,
Creates an iterator that yields the firstn elements, or fewerif the underlying iterator ends sooner.
take(n) yields elements untiln elements are yielded or the end ofthe iterator is reached (whichever happens first).The returned iterator is a prefix of lengthn if the original iteratorcontains at leastn elements, otherwise it contains all of the(fewer thann) elements of the original iterator.
§Examples
Basic usage:
leta = [1,2,3];letmutiter = a.into_iter().take(2);assert_eq!(iter.next(),Some(1));assert_eq!(iter.next(),Some(2));assert_eq!(iter.next(),None);take() is often used with an infinite iterator, to make it finite:
letmutiter = (0..).take(3);assert_eq!(iter.next(),Some(0));assert_eq!(iter.next(),Some(1));assert_eq!(iter.next(),Some(2));assert_eq!(iter.next(),None);If less thann elements are available,take will limit itself to the size of the underlying iterator:
letv = [1,2];letmutiter = v.into_iter().take(5);assert_eq!(iter.next(),Some(1));assert_eq!(iter.next(),Some(2));assert_eq!(iter.next(),None);Useby_ref to take from the iterator without consuming it, and thencontinue using the original iterator:
letmutwords = ["hello","world","of","Rust"].into_iter();// Take the first two words.lethello_world: Vec<_> = words.by_ref().take(2).collect();assert_eq!(hello_world,vec!["hello","world"]);// Collect the rest of the words.// We can only do this because we used `by_ref` earlier.letof_rust: Vec<_> = words.collect();assert_eq!(of_rust,vec!["of","Rust"]);1.0.0 ·Sourcefnscan<St, B, F>(self, initial_state: St, f: F) ->Scan<Self, St, F>ⓘ
fnscan<St, B, F>(self, initial_state: St, f: F) ->Scan<Self, St, F>ⓘ
An iterator adapter which, likefold, holds internal state, butunlikefold, produces a new iterator.
scan() takes two arguments: an initial value which seeds the internalstate, and a closure with two arguments, the first being a mutablereference to the internal state and the second an iterator element.The closure can assign to the internal state to share state betweeniterations.
On iteration, the closure will be applied to each element of theiterator and the return value from the closure, anOption, isreturned by thenext method. Thus the closure can returnSome(value) to yieldvalue, orNone to end the iteration.
§Examples
leta = [1,2,3,4];letmutiter = a.into_iter().scan(1, |state, x| {// each iteration, we'll multiply the state by the element ...*state =*state * x;// ... and terminate if the state exceeds 6if*state >6{returnNone; }// ... else yield the negation of the stateSome(-*state)});assert_eq!(iter.next(),Some(-1));assert_eq!(iter.next(),Some(-2));assert_eq!(iter.next(),Some(-6));assert_eq!(iter.next(),None);1.0.0 ·Sourcefnflat_map<U, F>(self, f: F) ->FlatMap<Self, U, F>ⓘ
fnflat_map<U, F>(self, f: F) ->FlatMap<Self, U, F>ⓘ
Creates an iterator that works like map, but flattens nested structure.
Themap adapter is very useful, but only when the closureargument produces values. If it produces an iterator instead, there’san extra layer of indirection.flat_map() will remove this extra layeron its own.
You can think offlat_map(f) as the semantic equivalentofmapping, and thenflattening as inmap(f).flatten().
Another way of thinking aboutflat_map():map’s closure returnsone item for each element, andflat_map()’s closure returns aniterator for each element.
§Examples
1.29.0 ·Sourcefnflatten(self) ->Flatten<Self>ⓘ
fnflatten(self) ->Flatten<Self>ⓘ
Creates an iterator that flattens nested structure.
This is useful when you have an iterator of iterators or an iterator ofthings that can be turned into iterators and you want to remove onelevel of indirection.
§Examples
Basic usage:
letdata =vec![vec![1,2,3,4],vec![5,6]];letflattened: Vec<_> = data.into_iter().flatten().collect();assert_eq!(flattened, [1,2,3,4,5,6]);Mapping and then flattening:
letwords = ["alpha","beta","gamma"];// chars() returns an iteratorletmerged: String = words.iter() .map(|s| s.chars()) .flatten() .collect();assert_eq!(merged,"alphabetagamma");You can also rewrite this in terms offlat_map(), which is preferablein this case since it conveys intent more clearly:
letwords = ["alpha","beta","gamma"];// chars() returns an iteratorletmerged: String = words.iter() .flat_map(|s| s.chars()) .collect();assert_eq!(merged,"alphabetagamma");Flattening works on anyIntoIterator type, includingOption andResult:
letoptions =vec![Some(123),Some(321),None,Some(231)];letflattened_options: Vec<_> = options.into_iter().flatten().collect();assert_eq!(flattened_options, [123,321,231]);letresults =vec![Ok(123),Ok(321),Err(456),Ok(231)];letflattened_results: Vec<_> = results.into_iter().flatten().collect();assert_eq!(flattened_results, [123,321,231]);Flattening only removes one level of nesting at a time:
letd3 = [[[1,2], [3,4]], [[5,6], [7,8]]];letd2: Vec<_> = d3.into_iter().flatten().collect();assert_eq!(d2, [[1,2], [3,4], [5,6], [7,8]]);letd1: Vec<_> = d3.into_iter().flatten().flatten().collect();assert_eq!(d1, [1,2,3,4,5,6,7,8]);Here we see thatflatten() does not perform a “deep” flatten.Instead, only one level of nesting is removed. That is, if youflatten() a three-dimensional array, the result will betwo-dimensional and not one-dimensional. To get a one-dimensionalstructure, you have toflatten() again.
Sourcefnmap_windows<F, R, const N:usize>(self, f: F) ->MapWindows<Self, F, N>ⓘ
🔬This is a nightly-only experimental API. (iter_map_windows #87155)
fnmap_windows<F, R, const N:usize>(self, f: F) ->MapWindows<Self, F, N>ⓘ
iter_map_windows #87155)Calls the given functionf for each contiguous window of sizeN overself and returns an iterator over the outputs off. Likeslice::windows(),the windows during mapping overlap as well.
In the following example, the closure is called three times with thearguments&['a', 'b'],&['b', 'c'] and&['c', 'd'] respectively.
#![feature(iter_map_windows)]letstrings ="abcd".chars() .map_windows(|[x, y]|format!("{}+{}", x, y)) .collect::<Vec<String>>();assert_eq!(strings,vec!["a+b","b+c","c+d"]);Note that the const parameterN is usually inferred by thedestructured argument in the closure.
The returned iterator yields 𝑘 −N + 1 items (where 𝑘 is the number ofitems yielded byself). If 𝑘 is less thanN, this method yields anempty iterator.
The returned iterator implementsFusedIterator, because onceselfreturnsNone, even if it returns aSome(T) again in the next iterations,we cannot put it into a contiguous array buffer, and thus the returned iteratorshould be fused.
§Panics
Panics ifN is zero. This check will most probably get changed to acompile time error before this method gets stabilized.
§Examples
Building the sums of neighboring numbers.
#![feature(iter_map_windows)]letmutit = [1,3,8,1].iter().map_windows(|&[a, b]| a + b);assert_eq!(it.next(),Some(4));// 1 + 3assert_eq!(it.next(),Some(11));// 3 + 8assert_eq!(it.next(),Some(9));// 8 + 1assert_eq!(it.next(),None);Since the elements in the following example implementCopy, we canjust copy the array and get an iterator over the windows.
#![feature(iter_map_windows)]letmutit ="ferris".chars().map_windows(|w:&[_;3]|*w);assert_eq!(it.next(),Some(['f','e','r']));assert_eq!(it.next(),Some(['e','r','r']));assert_eq!(it.next(),Some(['r','r','i']));assert_eq!(it.next(),Some(['r','i','s']));assert_eq!(it.next(),None);You can also use this function to check the sortedness of an iterator.For the simple case, rather useIterator::is_sorted.
#![feature(iter_map_windows)]letmutit = [0.5,1.0,3.5,3.0,8.5,8.5, f32::NAN].iter() .map_windows(|[a, b]| a <= b);assert_eq!(it.next(),Some(true));// 0.5 <= 1.0assert_eq!(it.next(),Some(true));// 1.0 <= 3.5assert_eq!(it.next(),Some(false));// 3.5 <= 3.0assert_eq!(it.next(),Some(true));// 3.0 <= 8.5assert_eq!(it.next(),Some(true));// 8.5 <= 8.5assert_eq!(it.next(),Some(false));// 8.5 <= NANassert_eq!(it.next(),None);For non-fused iterators, they are fused aftermap_windows.
#![feature(iter_map_windows)]#[derive(Default)]structNonFusedIterator { state: i32,}implIteratorforNonFusedIterator {typeItem = i32;fnnext(&mutself) ->Option<i32> {letval =self.state;self.state =self.state +1;// yields `0..5` first, then only even numbers since `6..`.ifval <5|| val %2==0{Some(val) }else{None} }}letmutiter = NonFusedIterator::default();// yields 0..5 first.assert_eq!(iter.next(),Some(0));assert_eq!(iter.next(),Some(1));assert_eq!(iter.next(),Some(2));assert_eq!(iter.next(),Some(3));assert_eq!(iter.next(),Some(4));// then we can see our iterator going back and forthassert_eq!(iter.next(),None);assert_eq!(iter.next(),Some(6));assert_eq!(iter.next(),None);assert_eq!(iter.next(),Some(8));assert_eq!(iter.next(),None);// however, with `.map_windows()`, it is fused.letmutiter = NonFusedIterator::default() .map_windows(|arr:&[_;2]|*arr);assert_eq!(iter.next(),Some([0,1]));assert_eq!(iter.next(),Some([1,2]));assert_eq!(iter.next(),Some([2,3]));assert_eq!(iter.next(),Some([3,4]));assert_eq!(iter.next(),None);// it will always return `None` after the first time.assert_eq!(iter.next(),None);assert_eq!(iter.next(),None);assert_eq!(iter.next(),None);1.0.0 ·Sourcefnfuse(self) ->Fuse<Self>ⓘwhere Self:Sized,
fnfuse(self) ->Fuse<Self>ⓘwhere Self:Sized,
Creates an iterator which ends after the firstNone.
After an iterator returnsNone, future calls may or may not yieldSome(T) again.fuse() adapts an iterator, ensuring that after aNone is given, it will always returnNone forever.
Note that theFuse wrapper is a no-op on iterators that implementtheFusedIterator trait.fuse() may therefore behave incorrectlyif theFusedIterator trait is improperly implemented.
§Examples
// an iterator which alternates between Some and NonestructAlternate { state: i32,}implIteratorforAlternate {typeItem = i32;fnnext(&mutself) ->Option<i32> {letval =self.state;self.state =self.state +1;// if it's even, Some(i32), else None(val %2==0).then_some(val) }}letmutiter = Alternate { state:0};// we can see our iterator going back and forthassert_eq!(iter.next(),Some(0));assert_eq!(iter.next(),None);assert_eq!(iter.next(),Some(2));assert_eq!(iter.next(),None);// however, once we fuse it...letmutiter = iter.fuse();assert_eq!(iter.next(),Some(4));assert_eq!(iter.next(),None);// it will always return `None` after the first time.assert_eq!(iter.next(),None);assert_eq!(iter.next(),None);assert_eq!(iter.next(),None);1.0.0 ·Sourcefninspect<F>(self, f: F) ->Inspect<Self, F>ⓘ
fninspect<F>(self, f: F) ->Inspect<Self, F>ⓘ
Does something with each element of an iterator, passing the value on.
When using iterators, you’ll often chain several of them together.While working on such code, you might want to check out what’shappening at various parts in the pipeline. To do that, inserta call toinspect().
It’s more common forinspect() to be used as a debugging tool than toexist in your final code, but applications may find it useful in certainsituations when errors need to be logged before being discarded.
§Examples
Basic usage:
leta = [1,4,2,3];// this iterator sequence is complex.letsum = a.iter() .cloned() .filter(|x| x %2==0) .fold(0, |sum, i| sum + i);println!("{sum}");// let's add some inspect() calls to investigate what's happeningletsum = a.iter() .cloned() .inspect(|x|println!("about to filter: {x}")) .filter(|x| x %2==0) .inspect(|x|println!("made it through filter: {x}")) .fold(0, |sum, i| sum + i);println!("{sum}");This will print:
6about to filter: 1about to filter: 4made it through filter: 4about to filter: 2made it through filter: 2about to filter: 36Logging errors before discarding them:
letlines = ["1","2","a"];letsum: i32 = lines .iter() .map(|line| line.parse::<i32>()) .inspect(|num| {if letErr(refe) =*num {println!("Parsing error: {e}"); } }) .filter_map(Result::ok) .sum();println!("Sum: {sum}");This will print:
Parsing error: invalid digit found in stringSum: 31.0.0 ·Sourcefnby_ref(&mut self) -> &mut Selfwhere Self:Sized,
fnby_ref(&mut self) -> &mut Selfwhere Self:Sized,
Creates a “by reference” adapter for this instance ofIterator.
Consuming method calls (direct or indirect calls tonext)on the “by reference” adapter will consume the original iterator,but ownership-taking methods (those with aself parameter)only take ownership of the “by reference” iterator.
This is useful for applying ownership-taking methods(such astake in the example below)without giving up ownership of the original iterator,so you can use the original iterator afterwards.
Usesimpl<I: Iterator + ?Sized> Iterator for &mut I { type Item = I::Item; ...}.
§Examples
letmutwords = ["hello","world","of","Rust"].into_iter();// Take the first two words.lethello_world: Vec<_> = words.by_ref().take(2).collect();assert_eq!(hello_world,vec!["hello","world"]);// Collect the rest of the words.// We can only do this because we used `by_ref` earlier.letof_rust: Vec<_> = words.collect();assert_eq!(of_rust,vec!["of","Rust"]);1.0.0 ·Sourcefncollect<B>(self) -> B
fncollect<B>(self) -> B
Transforms an iterator into a collection.
collect() can take anything iterable, and turn it into a relevantcollection. This is one of the more powerful methods in the standardlibrary, used in a variety of contexts.
The most basic pattern in whichcollect() is used is to turn onecollection into another. You take a collection, calliter on it,do a bunch of transformations, and thencollect() at the end.
collect() can also create instances of types that are not typicalcollections. For example, aString can be built fromchars,and an iterator ofResult<T, E> items can be collectedintoResult<Collection<T>, E>. See the examples below for more.
Becausecollect() is so general, it can cause problems with typeinference. As such,collect() is one of the few times you’ll seethe syntax affectionately known as the ‘turbofish’:::<>. Thishelps the inference algorithm understand specifically which collectionyou’re trying to collect into.
§Examples
Basic usage:
leta = [1,2,3];letdoubled: Vec<i32> = a.iter() .map(|x| x *2) .collect();assert_eq!(vec![2,4,6], doubled);Note that we needed the: Vec<i32> on the left-hand side. This is becausewe could collect into, for example, aVecDeque<T> instead:
usestd::collections::VecDeque;leta = [1,2,3];letdoubled: VecDeque<i32> = a.iter().map(|x| x *2).collect();assert_eq!(2, doubled[0]);assert_eq!(4, doubled[1]);assert_eq!(6, doubled[2]);Using the ‘turbofish’ instead of annotatingdoubled:
leta = [1,2,3];letdoubled = a.iter().map(|x| x *2).collect::<Vec<i32>>();assert_eq!(vec![2,4,6], doubled);Becausecollect() only cares about what you’re collecting into, you canstill use a partial type hint,_, with the turbofish:
leta = [1,2,3];letdoubled = a.iter().map(|x| x *2).collect::<Vec<_>>();assert_eq!(vec![2,4,6], doubled);Usingcollect() to make aString:
letchars = ['g','d','k','k','n'];lethello: String = chars.into_iter() .map(|x| xasu8) .map(|x| (x +1)aschar) .collect();assert_eq!("hello", hello);If you have a list ofResult<T, E>s, you can usecollect() tosee if any of them failed:
letresults = [Ok(1),Err("nope"),Ok(3),Err("bad")];letresult:Result<Vec<_>,&str> = results.into_iter().collect();// gives us the first errorassert_eq!(Err("nope"), result);letresults = [Ok(1),Ok(3)];letresult:Result<Vec<_>,&str> = results.into_iter().collect();// gives us the list of answersassert_eq!(Ok(vec![1,3]), result);Sourcefntry_collect<B>( &mut self,) -> <<Self::Item asTry>::Residual asResidual<B>>::TryType
🔬This is a nightly-only experimental API. (iterator_try_collect #94047)
fntry_collect<B>( &mut self,) -> <<Self::Item asTry>::Residual asResidual<B>>::TryType
iterator_try_collect #94047)Fallibly transforms an iterator into a collection, short circuiting ifa failure is encountered.
try_collect() is a variation ofcollect() that allows fallibleconversions during collection. Its main use case is simplifying conversions fromiterators yieldingOption<T> intoOption<Collection<T>>, or similarly for otherTrytypes (e.g.Result).
Importantly,try_collect() doesn’t require that the outerTry type also implementsFromIterator;only the inner type produced onTry::Output must implement it. Concretely,this means that collecting intoControlFlow<_, Vec<i32>> is valid becauseVec<i32> implementsFromIterator, even thoughControlFlow doesn’t.
Also, if a failure is encountered duringtry_collect(), the iterator is still valid andmay continue to be used, in which case it will continue iterating starting after the element thattriggered the failure. See the last example below for an example of how this works.
§Examples
Successfully collecting an iterator ofOption<i32> intoOption<Vec<i32>>:
#![feature(iterator_try_collect)]letu =vec![Some(1),Some(2),Some(3)];letv = u.into_iter().try_collect::<Vec<i32>>();assert_eq!(v,Some(vec![1,2,3]));Failing to collect in the same way:
#![feature(iterator_try_collect)]letu =vec![Some(1),Some(2),None,Some(3)];letv = u.into_iter().try_collect::<Vec<i32>>();assert_eq!(v,None);A similar example, but withResult:
#![feature(iterator_try_collect)]letu: Vec<Result<i32, ()>> =vec![Ok(1),Ok(2),Ok(3)];letv = u.into_iter().try_collect::<Vec<i32>>();assert_eq!(v,Ok(vec![1,2,3]));letu =vec![Ok(1),Ok(2),Err(()),Ok(3)];letv = u.into_iter().try_collect::<Vec<i32>>();assert_eq!(v,Err(()));Finally, evenControlFlow works, despite the fact that itdoesn’t implementFromIterator. Note also that the iterator cancontinue to be used, even if a failure is encountered:
#![feature(iterator_try_collect)]usecore::ops::ControlFlow::{Break, Continue};letu = [Continue(1), Continue(2), Break(3), Continue(4), Continue(5)];letmutit = u.into_iter();letv = it.try_collect::<Vec<_>>();assert_eq!(v, Break(3));letv = it.try_collect::<Vec<_>>();assert_eq!(v, Continue(vec![4,5]));Sourcefncollect_into<E>(self, collection:&mut E) ->&mut E
🔬This is a nightly-only experimental API. (iter_collect_into #94780)
fncollect_into<E>(self, collection:&mut E) ->&mut E
iter_collect_into #94780)Collects all the items from an iterator into a collection.
This method consumes the iterator and adds all its items to thepassed collection. The collection is then returned, so the call chaincan be continued.
This is useful when you already have a collection and want to addthe iterator items to it.
This method is a convenience method to callExtend::extend,but instead of being called on a collection, it’s called on an iterator.
§Examples
Basic usage:
#![feature(iter_collect_into)]leta = [1,2,3];letmutvec: Vec::<i32> =vec![0,1];a.iter().map(|x| x *2).collect_into(&mutvec);a.iter().map(|x| x *10).collect_into(&mutvec);assert_eq!(vec,vec![0,1,2,4,6,10,20,30]);Vec can have a manual set capacity to avoid reallocating it:
#![feature(iter_collect_into)]leta = [1,2,3];letmutvec: Vec::<i32> = Vec::with_capacity(6);a.iter().map(|x| x *2).collect_into(&mutvec);a.iter().map(|x| x *10).collect_into(&mutvec);assert_eq!(6, vec.capacity());assert_eq!(vec,vec![2,4,6,10,20,30]);The returned mutable reference can be used to continue the call chain:
#![feature(iter_collect_into)]leta = [1,2,3];letmutvec: Vec::<i32> = Vec::with_capacity(6);letcount = a.iter().collect_into(&mutvec).iter().count();assert_eq!(count, vec.len());assert_eq!(vec,vec![1,2,3]);letcount = a.iter().collect_into(&mutvec).iter().count();assert_eq!(count, vec.len());assert_eq!(vec,vec![1,2,3,1,2,3]);1.0.0 ·Sourcefnpartition<B, F>(self, f: F) ->(B, B)
fnpartition<B, F>(self, f: F) ->(B, B)
Consumes an iterator, creating two collections from it.
The predicate passed topartition() can returntrue, orfalse.partition() returns a pair, all of the elements for which it returnedtrue, and all of the elements for which it returnedfalse.
See alsois_partitioned() andpartition_in_place().
§Examples
Sourcefnpartition_in_place<'a, T, P>(self, predicate: P) ->usize
🔬This is a nightly-only experimental API. (iter_partition_in_place #62543)
fnpartition_in_place<'a, T, P>(self, predicate: P) ->usize
iter_partition_in_place #62543)Reorders the elements of this iteratorin-place according to the given predicate,such that all those that returntrue precede all those that returnfalse.Returns the number oftrue elements found.
The relative order of partitioned items is not maintained.
§Current implementation
The current algorithm tries to find the first element for which the predicate evaluatesto false and the last element for which it evaluates to true, and repeatedly swaps them.
Time complexity:O(n)
See alsois_partitioned() andpartition().
§Examples
Sourcefnis_partitioned<P>(self, predicate: P) ->bool
🔬This is a nightly-only experimental API. (iter_is_partitioned #62544)
fnis_partitioned<P>(self, predicate: P) ->bool
iter_is_partitioned #62544)Checks if the elements of this iterator are partitioned according to the given predicate,such that all those that returntrue precede all those that returnfalse.
See alsopartition() andpartition_in_place().
§Examples
1.27.0 ·Sourcefntry_fold<B, F, R>(&mut self, init: B, f: F) -> R
fntry_fold<B, F, R>(&mut self, init: B, f: F) -> R
An iterator method that applies a function as long as it returnssuccessfully, producing a single, final value.
try_fold() takes two arguments: an initial value, and a closure withtwo arguments: an ‘accumulator’, and an element. The closure eitherreturns successfully, with the value that the accumulator should havefor the next iteration, or it returns failure, with an error value thatis propagated back to the caller immediately (short-circuiting).
The initial value is the value the accumulator will have on the firstcall. If applying the closure succeeded against every element of theiterator,try_fold() returns the final accumulator as success.
Folding is useful whenever you have a collection of something, and wantto produce a single value from it.
§Note to Implementors
Several of the other (forward) methods have default implementations interms of this one, so try to implement this explicitly if it cando something better than the defaultfor loop implementation.
In particular, try to have this calltry_fold() on the internal partsfrom which this iterator is composed. If multiple calls are needed,the? operator may be convenient for chaining the accumulator valuealong, but beware any invariants that need to be upheld before thoseearly returns. This is a&mut self method, so iteration needs to beresumable after hitting an error here.
§Examples
Basic usage:
leta = [1,2,3];// the checked sum of all of the elements of the arrayletsum = a.into_iter().try_fold(0i8, |acc, x| acc.checked_add(x));assert_eq!(sum,Some(6));Short-circuiting:
leta = [10,20,30,100,40,50];letmutiter = a.into_iter();// This sum overflows when adding the 100 elementletsum = iter.try_fold(0i8, |acc, x| acc.checked_add(x));assert_eq!(sum,None);// Because it short-circuited, the remaining elements are still// available through the iterator.assert_eq!(iter.len(),2);assert_eq!(iter.next(),Some(40));While you cannotbreak from a closure, theControlFlow type allowsa similar idea:
usestd::ops::ControlFlow;lettriangular = (1..30).try_fold(0_i8, |prev, x| {if letSome(next) = prev.checked_add(x) { ControlFlow::Continue(next) }else{ ControlFlow::Break(prev) }});assert_eq!(triangular, ControlFlow::Break(120));lettriangular = (1..30).try_fold(0_u64, |prev, x| {if letSome(next) = prev.checked_add(x) { ControlFlow::Continue(next) }else{ ControlFlow::Break(prev) }});assert_eq!(triangular, ControlFlow::Continue(435));1.27.0 ·Sourcefntry_for_each<F, R>(&mut self, f: F) -> R
fntry_for_each<F, R>(&mut self, f: F) -> R
An iterator method that applies a fallible function to each item in theiterator, stopping at the first error and returning that error.
This can also be thought of as the fallible form offor_each()or as the stateless version oftry_fold().
§Examples
usestd::fs::rename;usestd::io::{stdout, Write};usestd::path::Path;letdata = ["no_tea.txt","stale_bread.json","torrential_rain.png"];letres = data.iter().try_for_each(|x|writeln!(stdout(),"{x}"));assert!(res.is_ok());letmutit = data.iter().cloned();letres = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));assert!(res.is_err());// It short-circuited, so the remaining items are still in the iterator:assert_eq!(it.next(),Some("stale_bread.json"));TheControlFlow type can be used with this method for the situationsin which you’d usebreak andcontinue in a normal loop:
1.0.0 ·Sourcefnfold<B, F>(self, init: B, f: F) -> B
fnfold<B, F>(self, init: B, f: F) -> B
Folds every element into an accumulator by applying an operation,returning the final result.
fold() takes two arguments: an initial value, and a closure with twoarguments: an ‘accumulator’, and an element. The closure returns the value thatthe accumulator should have for the next iteration.
The initial value is the value the accumulator will have on the firstcall.
After applying this closure to every element of the iterator,fold()returns the accumulator.
This operation is sometimes called ‘reduce’ or ‘inject’.
Folding is useful whenever you have a collection of something, and wantto produce a single value from it.
Note:fold(), and similar methods that traverse the entire iterator,might not terminate for infinite iterators, even on traits for which aresult is determinable in finite time.
Note:reduce() can be used to use the first element as the initialvalue, if the accumulator type and item type is the same.
Note:fold() combines elements in aleft-associative fashion. For associativeoperators like+, the order the elements are combined in is not important, but for non-associativeoperators like- the order will affect the final result.For aright-associative version offold(), seeDoubleEndedIterator::rfold().
§Note to Implementors
Several of the other (forward) methods have default implementations interms of this one, so try to implement this explicitly if it cando something better than the defaultfor loop implementation.
In particular, try to have this callfold() on the internal partsfrom which this iterator is composed.
§Examples
Basic usage:
leta = [1,2,3];// the sum of all of the elements of the arrayletsum = a.iter().fold(0, |acc, x| acc + x);assert_eq!(sum,6);Let’s walk through each step of the iteration here:
| element | acc | x | result |
|---|---|---|---|
| 0 | |||
| 1 | 0 | 1 | 1 |
| 2 | 1 | 2 | 3 |
| 3 | 3 | 3 | 6 |
And so, our final result,6.
This example demonstrates the left-associative nature offold():it builds a string, starting with an initial valueand continuing with each element from the front until the back:
letnumbers = [1,2,3,4,5];letzero ="0".to_string();letresult = numbers.iter().fold(zero, |acc,&x| {format!("({acc} + {x})")});assert_eq!(result,"(((((0 + 1) + 2) + 3) + 4) + 5)");It’s common for people who haven’t used iterators a lot touse afor loop with a list of things to build up a result. Thosecan be turned intofold()s:
1.51.0 ·Sourcefnreduce<F>(self, f: F) ->Option<Self::Item>
fnreduce<F>(self, f: F) ->Option<Self::Item>
Reduces the elements to a single one, by repeatedly applying a reducingoperation.
If the iterator is empty, returnsNone; otherwise, returns theresult of the reduction.
The reducing function is a closure with two arguments: an ‘accumulator’, and an element.For iterators with at least one element, this is the same asfold()with the first element of the iterator as the initial accumulator value, foldingevery subsequent element into it.
§Example
Sourcefntry_reduce<R>( &mut self, f: implFnMut(Self::Item, Self::Item) -> R,) -> <<R asTry>::Residual asResidual<Option<<R asTry>::Output>>>::TryType
🔬This is a nightly-only experimental API. (iterator_try_reduce #87053)
fntry_reduce<R>( &mut self, f: implFnMut(Self::Item, Self::Item) -> R,) -> <<R asTry>::Residual asResidual<Option<<R asTry>::Output>>>::TryType
iterator_try_reduce #87053)Reduces the elements to a single one by repeatedly applying a reducing operation. If theclosure returns a failure, the failure is propagated back to the caller immediately.
The return type of this method depends on the return type of the closure. If the closurereturnsResult<Self::Item, E>, then this function will returnResult<Option<Self::Item>, E>. If the closure returnsOption<Self::Item>, then this function will returnOption<Option<Self::Item>>.
When called on an empty iterator, this function will return eitherSome(None) orOk(None) depending on the type of the provided closure.
For iterators with at least one element, this is essentially the same as callingtry_fold() with the first element of the iterator as the initial accumulator value.
§Examples
Safely calculate the sum of a series of numbers:
#![feature(iterator_try_reduce)]letnumbers: Vec<usize> =vec![10,20,5,23,0];letsum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));assert_eq!(sum,Some(Some(58)));Determine when a reduction short circuited:
#![feature(iterator_try_reduce)]letnumbers =vec![1,2,3, usize::MAX,4,5];letsum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));assert_eq!(sum,None);Determine when a reduction was not performed because there are no elements:
1.0.0 ·Sourcefnall<F>(&mut self, f: F) ->bool
fnall<F>(&mut self, f: F) ->bool
Tests if every element of the iterator matches a predicate.
all() takes a closure that returnstrue orfalse. It appliesthis closure to each element of the iterator, and if they all returntrue, then so doesall(). If any of them returnfalse, itreturnsfalse.
all() is short-circuiting; in other words, it will stop processingas soon as it finds afalse, given that no matter what else happens,the result will also befalse.
An empty iterator returnstrue.
§Examples
Basic usage:
Stopping at the firstfalse:
1.0.0 ·Sourcefnany<F>(&mut self, f: F) ->bool
fnany<F>(&mut self, f: F) ->bool
Tests if any element of the iterator matches a predicate.
any() takes a closure that returnstrue orfalse. It appliesthis closure to each element of the iterator, and if any of them returntrue, then so doesany(). If they all returnfalse, itreturnsfalse.
any() is short-circuiting; in other words, it will stop processingas soon as it finds atrue, given that no matter what else happens,the result will also betrue.
An empty iterator returnsfalse.
§Examples
Basic usage:
Stopping at the firsttrue:
1.0.0 ·Sourcefnfind<P>(&mut self, predicate: P) ->Option<Self::Item>
fnfind<P>(&mut self, predicate: P) ->Option<Self::Item>
Searches for an element of an iterator that satisfies a predicate.
find() takes a closure that returnstrue orfalse. It appliesthis closure to each element of the iterator, and if any of them returntrue, thenfind() returnsSome(element). If they all returnfalse, it returnsNone.
find() is short-circuiting; in other words, it will stop processingas soon as the closure returnstrue.
Becausefind() takes a reference, and many iterators iterate overreferences, this leads to a possibly confusing situation where theargument is a double reference. You can see this effect in theexamples below, with&&x.
If you need the index of the element, seeposition().
§Examples
Basic usage:
leta = [1,2,3];assert_eq!(a.into_iter().find(|&x| x ==2),Some(2));assert_eq!(a.into_iter().find(|&x| x ==5),None);Stopping at the firsttrue:
leta = [1,2,3];letmutiter = a.into_iter();assert_eq!(iter.find(|&x| x ==2),Some(2));// we can still use `iter`, as there are more elements.assert_eq!(iter.next(),Some(3));Note thatiter.find(f) is equivalent toiter.filter(f).next().
1.30.0 ·Sourcefnfind_map<B, F>(&mut self, f: F) ->Option<B>
fnfind_map<B, F>(&mut self, f: F) ->Option<B>
Applies function to the elements of iterator and returnsthe first non-none result.
iter.find_map(f) is equivalent toiter.filter_map(f).next().
§Examples
Sourcefntry_find<R>( &mut self, f: implFnMut(&Self::Item) -> R,) -> <<R asTry>::Residual asResidual<Option<Self::Item>>>::TryType
🔬This is a nightly-only experimental API. (try_find #63178)
fntry_find<R>( &mut self, f: implFnMut(&Self::Item) -> R,) -> <<R asTry>::Residual asResidual<Option<Self::Item>>>::TryType
try_find #63178)Applies function to the elements of iterator and returnsthe first true result or the first error.
The return type of this method depends on the return type of the closure.If you returnResult<bool, E> from the closure, you’ll get aResult<Option<Self::Item>, E>.If you returnOption<bool> from the closure, you’ll get anOption<Option<Self::Item>>.
§Examples
#![feature(try_find)]leta = ["1","2","lol","NaN","5"];letis_my_num = |s:&str, search: i32| ->Result<bool, std::num::ParseIntError> {Ok(s.parse::<i32>()?== search)};letresult = a.into_iter().try_find(|&s| is_my_num(s,2));assert_eq!(result,Ok(Some("2")));letresult = a.into_iter().try_find(|&s| is_my_num(s,5));assert!(result.is_err());This also supports other types which implementTry, not justResult.
#![feature(try_find)]usestd::num::NonZero;leta = [3,5,7,4,9,0,11u32];letresult = a.into_iter().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));assert_eq!(result,Some(Some(4)));letresult = a.into_iter().take(3).try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));assert_eq!(result,Some(None));letresult = a.into_iter().rev().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));assert_eq!(result,None);1.0.0 ·Sourcefnposition<P>(&mut self, predicate: P) ->Option<usize>
fnposition<P>(&mut self, predicate: P) ->Option<usize>
Searches for an element in an iterator, returning its index.
position() takes a closure that returnstrue orfalse. It appliesthis closure to each element of the iterator, and if one of themreturnstrue, thenposition() returnsSome(index). If all ofthem returnfalse, it returnsNone.
position() is short-circuiting; in other words, it will stopprocessing as soon as it finds atrue.
§Overflow Behavior
The method does no guarding against overflows, so if there are morethanusize::MAX non-matching elements, it either produces the wrongresult or panics. If overflow checks are enabled, a panic isguaranteed.
§Panics
This function might panic if the iterator has more thanusize::MAXnon-matching elements.
§Examples
Basic usage:
leta = [1,2,3];assert_eq!(a.into_iter().position(|x| x ==2),Some(1));assert_eq!(a.into_iter().position(|x| x ==5),None);Stopping at the firsttrue:
1.0.0 ·Sourcefnrposition<P>(&mut self, predicate: P) ->Option<usize>
fnrposition<P>(&mut self, predicate: P) ->Option<usize>
Searches for an element in an iterator from the right, returning itsindex.
rposition() takes a closure that returnstrue orfalse. It appliesthis closure to each element of the iterator, starting from the end,and if one of them returnstrue, thenrposition() returnsSome(index). If all of them returnfalse, it returnsNone.
rposition() is short-circuiting; in other words, it will stopprocessing as soon as it finds atrue.
§Examples
Basic usage:
leta = [1,2,3];assert_eq!(a.into_iter().rposition(|x| x ==3),Some(2));assert_eq!(a.into_iter().rposition(|x| x ==5),None);Stopping at the firsttrue:
1.0.0 ·Sourcefnmax(self) ->Option<Self::Item>
fnmax(self) ->Option<Self::Item>
1.0.0 ·Sourcefnmin(self) ->Option<Self::Item>
fnmin(self) ->Option<Self::Item>
1.6.0 ·Sourcefnmax_by_key<B, F>(self, f: F) ->Option<Self::Item>
fnmax_by_key<B, F>(self, f: F) ->Option<Self::Item>
1.15.0 ·Sourcefnmax_by<F>(self, compare: F) ->Option<Self::Item>
fnmax_by<F>(self, compare: F) ->Option<Self::Item>
1.6.0 ·Sourcefnmin_by_key<B, F>(self, f: F) ->Option<Self::Item>
fnmin_by_key<B, F>(self, f: F) ->Option<Self::Item>
1.15.0 ·Sourcefnmin_by<F>(self, compare: F) ->Option<Self::Item>
fnmin_by<F>(self, compare: F) ->Option<Self::Item>
1.0.0 ·Sourcefnrev(self) ->Rev<Self>ⓘwhere Self:Sized +DoubleEndedIterator,
fnrev(self) ->Rev<Self>ⓘwhere Self:Sized +DoubleEndedIterator,
Reverses an iterator’s direction.
Usually, iterators iterate from left to right. After usingrev(),an iterator will instead iterate from right to left.
This is only possible if the iterator has an end, sorev() onlyworks onDoubleEndedIterators.
§Examples
1.0.0 ·Sourcefnunzip<A, B, FromA, FromB>(self) ->(FromA, FromB)
fnunzip<A, B, FromA, FromB>(self) ->(FromA, FromB)
Converts an iterator of pairs into a pair of containers.
unzip() consumes an entire iterator of pairs, producing twocollections: one from the left elements of the pairs, and onefrom the right elements.
This function is, in some sense, the opposite ofzip.
§Examples
leta = [(1,2), (3,4), (5,6)];let(left, right): (Vec<_>, Vec<_>) = a.into_iter().unzip();assert_eq!(left, [1,3,5]);assert_eq!(right, [2,4,6]);// you can also unzip multiple nested tuples at onceleta = [(1, (2,3)), (4, (5,6))];let(x, (y, z)): (Vec<_>, (Vec<_>, Vec<_>)) = a.into_iter().unzip();assert_eq!(x, [1,4]);assert_eq!(y, [2,5]);assert_eq!(z, [3,6]);1.36.0 ·Sourcefncopied<'a, T>(self) ->Copied<Self>ⓘ
fncopied<'a, T>(self) ->Copied<Self>ⓘ
Creates an iterator which copies all of its elements.
This is useful when you have an iterator over&T, but you need aniterator overT.
§Examples
1.0.0 ·Sourcefncloned<'a, T>(self) ->Cloned<Self>ⓘ
fncloned<'a, T>(self) ->Cloned<Self>ⓘ
Creates an iterator whichclones all of its elements.
This is useful when you have an iterator over&T, but you need aniterator overT.
There is no guarantee whatsoever about theclone method actuallybeing calledor optimized away. So code should not depend oneither.
§Examples
Basic usage:
leta = [1,2,3];letv_cloned: Vec<_> = a.iter().cloned().collect();// cloned is the same as .map(|&x| x), for integersletv_map: Vec<_> = a.iter().map(|&x| x).collect();assert_eq!(v_cloned, [1,2,3]);assert_eq!(v_map, [1,2,3]);To get the best performance, try to clone late:
leta = [vec![0_u8,1,2],vec![3,4],vec![23]];// don't do this:letslower: Vec<_> = a.iter().cloned().filter(|s| s.len() ==1).collect();assert_eq!(&[vec![23]],&slower[..]);// instead call `cloned` lateletfaster: Vec<_> = a.iter().filter(|s| s.len() ==1).cloned().collect();assert_eq!(&[vec![23]],&faster[..]);1.0.0 ·Sourcefncycle(self) ->Cycle<Self>ⓘ
fncycle(self) ->Cycle<Self>ⓘ
Repeats an iterator endlessly.
Instead of stopping atNone, the iterator will instead start again,from the beginning. After iterating again, it will start at thebeginning again. And again. And again. Forever. Note that in case theoriginal iterator is empty, the resulting iterator will also be empty.
§Examples
Sourcefnarray_chunks<const N:usize>(self) ->ArrayChunks<Self, N>ⓘwhere Self:Sized,
🔬This is a nightly-only experimental API. (iter_array_chunks #100450)
fnarray_chunks<const N:usize>(self) ->ArrayChunks<Self, N>ⓘwhere Self:Sized,
iter_array_chunks #100450)Returns an iterator overN elements of the iterator at a time.
The chunks do not overlap. IfN does not divide the length of theiterator, then the last up toN-1 elements will be omitted and can beretrieved from the.into_remainder()function of the iterator.
§Panics
Panics ifN is zero.
§Examples
Basic usage:
1.11.0 ·Sourcefnsum<S>(self) -> S
fnsum<S>(self) -> S
Sums the elements of an iterator.
Takes each element, adds them together, and returns the result.
An empty iterator returns theadditive identity (“zero”) of the type,which is0 for integers and-0.0 for floats.
sum() can be used to sum any type implementingSum,includingOption andResult.
§Panics
When callingsum() and a primitive integer type is being returned, thismethod will panic if the computation overflows and overflow checks areenabled.
§Examples
1.11.0 ·Sourcefnproduct<P>(self) -> P
fnproduct<P>(self) -> P
Iterates over the entire iterator, multiplying all the elements
An empty iterator returns the one value of the type.
product() can be used to multiply any type implementingProduct,includingOption andResult.
§Panics
When callingproduct() and a primitive integer type is being returned,method will panic if the computation overflows and overflow checks areenabled.
§Examples
1.5.0 ·Sourcefncmp<I>(self, other: I) ->Ordering
fncmp<I>(self, other: I) ->Ordering
Lexicographically compares the elements of thisIterator with thoseof another.
§Examples
Sourcefncmp_by<I, F>(self, other: I, cmp: F) ->Ordering
🔬This is a nightly-only experimental API. (iter_order_by #64295)
fncmp_by<I, F>(self, other: I, cmp: F) ->Ordering
iter_order_by #64295)Lexicographically compares the elements of thisIterator with thoseof another with respect to the specified comparison function.
§Examples
#![feature(iter_order_by)]usestd::cmp::Ordering;letxs = [1,2,3,4];letys = [1,4,9,16];assert_eq!(xs.into_iter().cmp_by(ys, |x, y| x.cmp(&y)), Ordering::Less);assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (x * x).cmp(&y)), Ordering::Equal);assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (2* x).cmp(&y)), Ordering::Greater);1.5.0 ·Sourcefnpartial_cmp<I>(self, other: I) ->Option<Ordering>
fnpartial_cmp<I>(self, other: I) ->Option<Ordering>
Lexicographically compares thePartialOrd elements ofthisIterator with those of another. The comparison works like short-circuitevaluation, returning a result without comparing the remaining elements.As soon as an order can be determined, the evaluation stops and a result is returned.
§Examples
usestd::cmp::Ordering;assert_eq!([1.].iter().partial_cmp([1.].iter()),Some(Ordering::Equal));assert_eq!([1.].iter().partial_cmp([1.,2.].iter()),Some(Ordering::Less));assert_eq!([1.,2.].iter().partial_cmp([1.].iter()),Some(Ordering::Greater));For floating-point numbers, NaN does not have a total order and will resultinNone when compared:
The results are determined by the order of evaluation.
Sourcefnpartial_cmp_by<I, F>(self, other: I, partial_cmp: F) ->Option<Ordering>
🔬This is a nightly-only experimental API. (iter_order_by #64295)
fnpartial_cmp_by<I, F>(self, other: I, partial_cmp: F) ->Option<Ordering>
iter_order_by #64295)Lexicographically compares the elements of thisIterator with thoseof another with respect to the specified comparison function.
§Examples
#![feature(iter_order_by)]usestd::cmp::Ordering;letxs = [1.0,2.0,3.0,4.0];letys = [1.0,4.0,9.0,16.0];assert_eq!( xs.iter().partial_cmp_by(ys, |x, y| x.partial_cmp(&y)),Some(Ordering::Less));assert_eq!( xs.iter().partial_cmp_by(ys, |x, y| (x * x).partial_cmp(&y)),Some(Ordering::Equal));assert_eq!( xs.iter().partial_cmp_by(ys, |x, y| (2.0* x).partial_cmp(&y)),Some(Ordering::Greater));Sourcefneq_by<I, F>(self, other: I, eq: F) ->bool
🔬This is a nightly-only experimental API. (iter_order_by #64295)
fneq_by<I, F>(self, other: I, eq: F) ->bool
iter_order_by #64295)1.5.0 ·Sourcefnlt<I>(self, other: I) ->bool
fnlt<I>(self, other: I) ->bool
Determines if the elements of thisIterator arelexicographicallyless than those of another.
§Examples
1.5.0 ·Sourcefnle<I>(self, other: I) ->bool
fnle<I>(self, other: I) ->bool
Determines if the elements of thisIterator arelexicographicallyless or equal to those of another.
§Examples
1.5.0 ·Sourcefngt<I>(self, other: I) ->bool
fngt<I>(self, other: I) ->bool
Determines if the elements of thisIterator arelexicographicallygreater than those of another.
§Examples
1.5.0 ·Sourcefnge<I>(self, other: I) ->bool
fnge<I>(self, other: I) ->bool
Determines if the elements of thisIterator arelexicographicallygreater than or equal to those of another.
§Examples
1.82.0 ·Sourcefnis_sorted(self) ->bool
fnis_sorted(self) ->bool
Checks if the elements of this iterator are sorted.
That is, for each elementa and its following elementb,a <= b must hold. If theiterator yields exactly zero or one element,true is returned.
Note that ifSelf::Item is onlyPartialOrd, but notOrd, the above definitionimplies that this function returnsfalse if any two consecutive items are notcomparable.
§Examples
1.82.0 ·Sourcefnis_sorted_by<F>(self, compare: F) ->bool
fnis_sorted_by<F>(self, compare: F) ->bool
Checks if the elements of this iterator are sorted using the given comparator function.
Instead of usingPartialOrd::partial_cmp, this function uses the givencomparefunction to determine whether two elements are to be considered in sorted order.
§Examples
assert!([1,2,2,9].iter().is_sorted_by(|a, b| a <= b));assert!(![1,2,2,9].iter().is_sorted_by(|a, b| a < b));assert!([0].iter().is_sorted_by(|a, b|true));assert!([0].iter().is_sorted_by(|a, b|false));assert!(std::iter::empty::<i32>().is_sorted_by(|a, b|false));assert!(std::iter::empty::<i32>().is_sorted_by(|a, b|true));1.82.0 ·Sourcefnis_sorted_by_key<F, K>(self, f: F) ->bool
fnis_sorted_by_key<F, K>(self, f: F) ->bool
Checks if the elements of this iterator are sorted using the given key extractionfunction.
Instead of comparing the iterator’s elements directly, this function compares the keys ofthe elements, as determined byf. Apart from that, it’s equivalent tois_sorted; seeits documentation for more information.
§Examples
Implementors§
Source§impl<'a>Iterator forMessages<'a>
Available on(Android or Linux or Cygwin) and Unix only.
impl<'a>Iterator forMessages<'a>
typeItem =Result<AncillaryData<'a>,AncillaryError>
Source§impl<'a>Iterator forScmCredentials<'a>
Available on(Android or Linux or Cygwin) and Unix only.
impl<'a>Iterator forScmCredentials<'a>
typeItem =SocketCred
impl<'a, I, A> !Iterator for &'aBox<[I], A>where A:Allocator,
This implementation is required to make sure that the&Box<[I]>: IntoIteratorimplementation doesn’t overlap withIntoIterator for T where T: Iterator blanket.
impl<'a, I, A> !Iterator for &'a mutBox<[I], A>where A:Allocator,
This implementation is required to make sure that the&mut Box<[I]>: IntoIteratorimplementation doesn’t overlap withIntoIterator for T where T: Iterator blanket.
1.0.0 ·Source§impl<'a, K, V>Iterator for std::collections::btree_map::Iter<'a, K, V>where K: 'a, V: 'a,
impl<'a, K, V>Iterator for std::collections::btree_map::Iter<'a, K, V>where K: 'a, V: 'a,
1.5.0 ·Source§impl<'a, P>Iterator forMatchIndices<'a, P>where P:Pattern,
impl<'a, P>Iterator forMatchIndices<'a, P>where P:Pattern,
1.5.0 ·Source§impl<'a, P>Iterator forRMatchIndices<'a, P>
impl<'a, P>Iterator forRMatchIndices<'a, P>
1.0.0 ·Source§impl<'a, P>Iterator forRSplitTerminator<'a, P>
impl<'a, P>Iterator forRSplitTerminator<'a, P>
1.51.0 ·Source§impl<'a, P>Iterator for std::str::SplitInclusive<'a, P>where P:Pattern,
impl<'a, P>Iterator for std::str::SplitInclusive<'a, P>where P:Pattern,
1.0.0 ·Source§impl<'a, T>Iterator for std::collections::btree_set::SymmetricDifference<'a, T>where T:Ord,
impl<'a, T>Iterator for std::collections::btree_set::SymmetricDifference<'a, T>where T:Ord,
1.0.0 ·Source§impl<'a, T, A>Iterator for std::collections::btree_set::Difference<'a, T, A>
impl<'a, T, A>Iterator for std::collections::btree_set::Difference<'a, T, A>
1.0.0 ·Source§impl<'a, T, A>Iterator for std::collections::btree_set::Intersection<'a, T, A>
impl<'a, T, A>Iterator for std::collections::btree_set::Intersection<'a, T, A>
1.77.0 ·Source§impl<'a, T, P>Iterator forChunkByMut<'a, T, P>
impl<'a, T, P>Iterator forChunkByMut<'a, T, P>
1.0.0 ·Source§impl<'a, T, P>Iterator forRSplitNMut<'a, T, P>
impl<'a, T, P>Iterator forRSplitNMut<'a, T, P>
1.51.0 ·Source§impl<'a, T, P>Iterator for std::slice::SplitInclusive<'a, T, P>
impl<'a, T, P>Iterator for std::slice::SplitInclusive<'a, T, P>
1.51.0 ·Source§impl<'a, T, P>Iterator forSplitInclusiveMut<'a, T, P>
impl<'a, T, P>Iterator forSplitInclusiveMut<'a, T, P>
1.0.0 ·Source§impl<'a, T, S>Iterator for std::collections::hash_set::Difference<'a, T, S>
impl<'a, T, S>Iterator for std::collections::hash_set::Difference<'a, T, S>
1.0.0 ·Source§impl<'a, T, S>Iterator for std::collections::hash_set::Intersection<'a, T, S>
impl<'a, T, S>Iterator for std::collections::hash_set::Intersection<'a, T, S>
1.0.0 ·Source§impl<'a, T, S>Iterator for std::collections::hash_set::SymmetricDifference<'a, T, S>
impl<'a, T, S>Iterator for std::collections::hash_set::SymmetricDifference<'a, T, S>
Source§impl<G>Iterator forFromCoroutine<G>
impl<G>Iterator forFromCoroutine<G>
1.0.0 ·Source§impl<I>Iterator for&mut I
ImplementsIterator for mutable references to iterators, such as those produced byIterator::by_ref.
impl<I>Iterator for&mut I
ImplementsIterator for mutable references to iterators, such as those produced byIterator::by_ref.
This implementation passes all method calls on to the original iterator.
1.9.0 ·Source§impl<I>Iterator forDecodeUtf16<I>
impl<I>Iterator forDecodeUtf16<I>
Source§impl<I>Iterator forIntersperse<I>
impl<I>Iterator forIntersperse<I>
1.0.0 ·Source§impl<I>Iterator forRev<I>where I:DoubleEndedIterator,
impl<I>Iterator forRev<I>where I:DoubleEndedIterator,
impl<I, A> !Iterator forBox<[I], A>where A:Allocator,
This implementation is required to make sure that theBox<[I]>: IntoIteratorimplementation doesn’t overlap withIntoIterator for T where T: Iterator blanket.