Movatterモバイル変換


[0]ホーム

URL:


Iterator

std::iter

TraitIterator 

1.0.0 ·Source
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§

1.0.0 ·Source

typeItem

The type of the elements being iterated over.

Required Methods§

1.0.0 ·Source

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§

Source

fnnext_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)

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 4

Split a string and get the first three items.

#![feature(iter_next_chunk)]letquote ="not all those who wander are lost";let[first, second, third] = quote.split_whitespace().next_chunk().unwrap();assert_eq!(first,"not");assert_eq!(second,"all");assert_eq!(third,"those");
1.0.0 ·Source

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:

// an infinite iterator has no upper bound// and the maximum possible lower boundletiter =0..;assert_eq!((usize::MAX,None), iter.size_hint());
1.0.0 ·Source

fncount(self) ->usize
where 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
leta = [1,2,3];assert_eq!(a.iter().count(),3);leta = [1,2,3,4,5];assert_eq!(a.iter().count(),5);
1.0.0 ·Source

fnlast(self) ->Option<Self::Item>
where Self:Sized,

Consumes the iterator, returning the last element.

This method will evaluate the iterator until it returnsNone. Whiledoing so, it keeps track of the current element. AfterNone isreturned,last() will then return the last element it saw.

§Examples
leta = [1,2,3];assert_eq!(a.into_iter().last(),Some(3));leta = [1,2,3,4,5];assert_eq!(a.into_iter().last(),Some(5));
Source

fnadvance_by(&mut self, n:usize) ->Result<(),NonZero<usize>>

🔬This is a nightly-only experimental API. (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
#![feature(iter_advance_by)]usestd::num::NonZero;leta = [1,2,3,4];letmutiter = a.into_iter();assert_eq!(iter.advance_by(2),Ok(()));assert_eq!(iter.next(),Some(3));assert_eq!(iter.advance_by(0),Ok(()));assert_eq!(iter.advance_by(100),Err(NonZero::new(99).unwrap()));// only `4` was skipped
1.0.0 ·Source

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:

leta = [1,2,3];assert_eq!(a.into_iter().nth(1),Some(2));

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:

leta = [1,2,3];assert_eq!(a.into_iter().nth(10),None);
1.28.0 ·Source

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
leta = [0,1,2,3,4,5];letmutiter = a.into_iter().step_by(2);assert_eq!(iter.next(),Some(0));assert_eq!(iter.next(),Some(2));assert_eq!(iter.next(),Some(4));assert_eq!(iter.next(),None);
1.0.0 ·Source

fnchain<U>(self, other: U) ->Chain<Self, <U asIntoIterator>::IntoIter>
where Self:Sized, U:IntoIterator<Item = Self::Item>,

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>:

#[cfg(windows)]fnos_str_to_utf16(s:&std::ffi::OsStr) -> Vec<u16> {usestd::os::windows::ffi::OsStrExt;    s.encode_wide().chain(std::iter::once(0)).collect()}
1.0.0 ·Source

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:

letmutzipped = a    .into_iter()    .map(|x| x *2)    .skip(1)    .zip(b.into_iter().map(|x| x *2).skip(1));
Source

fnintersperse(self, separator: Self::Item) ->Intersperse<Self>
where Self:Sized, Self::Item:Clone,

🔬This is a nightly-only experimental API. (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:

#![feature(iter_intersperse)]letwords = ["Hello","World","!"];lethello: String = words.into_iter().intersperse(" ").collect();assert_eq!(hello,"Hello World !");
Source

fnintersperse_with<G>(self, separator: G) ->IntersperseWith<Self, G>
where Self:Sized, G:FnMut() -> Self::Item,

🔬This is a nightly-only experimental API. (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 ·Source

fnmap<B, F>(self, f: F) ->Map<Self, F>
where Self:Sized, F:FnMut(Self::Item) -> B,

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():

// don't do this:(0..5).map(|x|println!("{x}"));// it won't even execute, as it is lazy. Rust will warn you about this.// Instead, use a for-loop:forxin0..5{println!("{x}");}
1.21.0 ·Source

fnfor_each<F>(self, f: F)
where Self:Sized, F:FnMut(Self::Item),

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:

(0..5).flat_map(|x| (x *100)..(x *110))      .enumerate()      .filter(|&(i, x)| (i + x) %3==0)      .for_each(|(i, x)|println!("{i}:{x}"));
1.0.0 ·Source

fnfilter<P>(self, predicate: P) ->Filter<Self, P>
where Self:Sized, P:FnMut(&Self::Item) ->bool,

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 ·Source

fnfilter_map<B, F>(self, f: F) ->FilterMap<Self, F>
where Self:Sized, F:FnMut(Self::Item) ->Option<B>,

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:

leta = ["1","two","NaN","four","5"];letmutiter = a.iter().filter_map(|s| s.parse().ok());assert_eq!(iter.next(),Some(1));assert_eq!(iter.next(),Some(5));assert_eq!(iter.next(),None);

Here’s the same example, but withfilter andmap:

leta = ["1","two","NaN","four","5"];letmutiter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());assert_eq!(iter.next(),Some(1));assert_eq!(iter.next(),Some(5));assert_eq!(iter.next(),None);
1.0.0 ·Source

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
leta = ['a','b','c'];letmutiter = a.into_iter().enumerate();assert_eq!(iter.next(),Some((0,'a')));assert_eq!(iter.next(),Some((1,'b')));assert_eq!(iter.next(),Some((2,'c')));assert_eq!(iter.next(),None);
1.0.0 ·Source

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 ·Source

fnskip_while<P>(self, predicate: P) ->SkipWhile<Self, P>
where Self:Sized, P:FnMut(&Self::Item) ->bool,

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:

leta = [-1,0,1, -2];letmutiter = a.into_iter().skip_while(|&x| x <0);assert_eq!(iter.next(),Some(0));assert_eq!(iter.next(),Some(1));// while this would have been false, since we already got a false,// skip_while() isn't used any moreassert_eq!(iter.next(),Some(-2));assert_eq!(iter.next(),None);
1.0.0 ·Source

fntake_while<P>(self, predicate: P) ->TakeWhile<Self, P>
where Self:Sized, P:FnMut(&Self::Item) ->bool,

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 ·Source

fnmap_while<B, P>(self, predicate: P) ->MapWhile<Self, P>
where Self:Sized, P:FnMut(Self::Item) ->Option<B>,

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 ·Source

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
leta = [1,2,3];letmutiter = a.into_iter().skip(2);assert_eq!(iter.next(),Some(3));assert_eq!(iter.next(),None);
1.0.0 ·Source

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 ·Source

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>,

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 ·Source

fnflat_map<U, F>(self, f: F) ->FlatMap<Self, U, F>
where Self:Sized, U:IntoIterator, F:FnMut(Self::Item) -> U,

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
letwords = ["alpha","beta","gamma"];// chars() returns an iteratorletmerged: String = words.iter()                          .flat_map(|s| s.chars())                          .collect();assert_eq!(merged,"alphabetagamma");
1.29.0 ·Source

fnflatten(self) ->Flatten<Self>
where Self:Sized, Self::Item:IntoIterator,

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.

Source

fnmap_windows<F, R, const N:usize>(self, f: F) ->MapWindows<Self, F, N>
where Self:Sized, F:FnMut(&[Self::Item;N]) -> R,

🔬This is a nightly-only experimental API. (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.

#![feature(iter_map_windows)]letiter = std::iter::repeat(0).map_windows(|&[]| ());
§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 ·Source

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 ·Source

fninspect<F>(self, f: F) ->Inspect<Self, F>
where Self:Sized, F:FnMut(&Self::Item),

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: 36

Logging 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: 3
1.0.0 ·Source

fnby_ref(&mut self) -> &mut Self
where 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 ·Source

fncollect<B>(self) -> B
where B:FromIterator<Self::Item>, Self:Sized,

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);
Source

fntry_collect<B>( &mut self,) -> <<Self::Item asTry>::Residual asResidual<B>>::TryType
where Self:Sized, Self::Item:Try, <Self::Item asTry>::Residual:Residual<B>, B:FromIterator<<Self::Item asTry>::Output>,

🔬This is a nightly-only experimental API. (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]));
Source

fncollect_into<E>(self, collection:&mut E) ->&mut E
where E:Extend<Self::Item>, Self:Sized,

🔬This is a nightly-only experimental API. (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 ·Source

fnpartition<B, F>(self, f: F) ->(B, B)
where Self:Sized, B:Default +Extend<Self::Item>, F:FnMut(&Self::Item) ->bool,

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
leta = [1,2,3];let(even, odd): (Vec<_>, Vec<_>) = a    .into_iter()    .partition(|n| n %2==0);assert_eq!(even, [2]);assert_eq!(odd, [1,3]);
Source

fnpartition_in_place<'a, T, P>(self, predicate: P) ->usize
where T: 'a, Self:Sized +DoubleEndedIterator<Item =&'a mut T>, P:FnMut(&T) ->bool,

🔬This is a nightly-only experimental API. (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
#![feature(iter_partition_in_place)]letmuta = [1,2,3,4,5,6,7];// Partition in-place between evens and oddsleti = a.iter_mut().partition_in_place(|n| n %2==0);assert_eq!(i,3);assert!(a[..i].iter().all(|n| n %2==0));// evensassert!(a[i..].iter().all(|n| n %2==1));// odds
Source

fnis_partitioned<P>(self, predicate: P) ->bool
where Self:Sized, P:FnMut(Self::Item) ->bool,

🔬This is a nightly-only experimental API. (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
#![feature(iter_is_partitioned)]assert!("Iterator".chars().is_partitioned(char::is_uppercase));assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
1.27.0 ·Source

fntry_fold<B, F, R>(&mut self, init: B, f: F) -> R
where Self:Sized, F:FnMut(B, Self::Item) -> R, R:Try<Output = B>,

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 ·Source

fntry_for_each<F, R>(&mut self, f: F) -> R
where Self:Sized, F:FnMut(Self::Item) -> R, R:Try<Output =()>,

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:

usestd::ops::ControlFlow;letr = (2..100).try_for_each(|x| {if323% x ==0{returnControlFlow::Break(x)    }    ControlFlow::Continue(())});assert_eq!(r, ControlFlow::Break(17));
1.0.0 ·Source

fnfold<B, F>(self, init: B, f: F) -> B
where Self:Sized, F:FnMut(B, Self::Item) -> 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:

elementaccxresult
0
1011
2123
3336

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:

letnumbers = [1,2,3,4,5];letmutresult =0;// for loop:foriin&numbers {    result = result + i;}// fold:letresult2 = numbers.iter().fold(0, |acc,&x| acc + x);// they're the sameassert_eq!(result, result2);
1.51.0 ·Source

fnreduce<F>(self, f: F) ->Option<Self::Item>
where Self:Sized, F:FnMut(Self::Item, Self::Item) -> 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
letreduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap_or(0);assert_eq!(reduced,45);// Which is equivalent to doing it with `fold`:letfolded: i32 = (1..10).fold(0, |acc, e| acc + e);assert_eq!(reduced, folded);
Source

fntry_reduce<R>( &mut self, f: implFnMut(Self::Item, Self::Item) -> R,) -> <<R asTry>::Residual asResidual<Option<<R asTry>::Output>>>::TryType
where Self:Sized, R:Try<Output = Self::Item>, <R asTry>::Residual:Residual<Option<Self::Item>>,

🔬This is a nightly-only experimental API. (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:

#![feature(iterator_try_reduce)]letnumbers: Vec<usize> = Vec::new();letsum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));assert_eq!(sum,Some(None));

Use aResult instead of anOption:

#![feature(iterator_try_reduce)]letnumbers =vec!["1","2","3","4","5"];letmax:Result<Option<_>, <usizeasstd::str::FromStr>::Err> =    numbers.into_iter().try_reduce(|x, y| {ifx.parse::<usize>()?> y.parse::<usize>()?{Ok(x) }else{Ok(y) }    });assert_eq!(max,Ok(Some("5")));
1.0.0 ·Source

fnall<F>(&mut self, f: F) ->bool
where Self:Sized, F:FnMut(Self::Item) ->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:

leta = [1,2,3];assert!(a.into_iter().all(|x| x >0));assert!(!a.into_iter().all(|x| x >2));

Stopping at the firstfalse:

leta = [1,2,3];letmutiter = a.into_iter();assert!(!iter.all(|x|x !=2));// we can still use `iter`, as there are more elements.assert_eq!(iter.next(),Some(3));
1.0.0 ·Source

fnany<F>(&mut self, f: F) ->bool
where Self:Sized, F:FnMut(Self::Item) ->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:

leta = [1,2,3];assert!(a.into_iter().any(|x| x >0));assert!(!a.into_iter().any(|x| x >5));

Stopping at the firsttrue:

leta = [1,2,3];letmutiter = a.into_iter();assert!(iter.any(|x|x !=2));// we can still use `iter`, as there are more elements.assert_eq!(iter.next(),Some(2));
1.0.0 ·Source

fnfind<P>(&mut self, predicate: P) ->Option<Self::Item>
where Self:Sized, P:FnMut(&Self::Item) ->bool,

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 ·Source

fnfind_map<B, F>(&mut self, f: F) ->Option<B>
where Self:Sized, F:FnMut(Self::Item) ->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
leta = ["lol","NaN","2","5"];letfirst_number = a.iter().find_map(|s| s.parse().ok());assert_eq!(first_number,Some(2));
Source

fntry_find<R>( &mut self, f: implFnMut(&Self::Item) -> R,) -> <<R asTry>::Residual asResidual<Option<Self::Item>>>::TryType
where Self:Sized, R:Try<Output =bool>, <R asTry>::Residual:Residual<Option<Self::Item>>,

🔬This is a nightly-only experimental API. (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 ·Source

fnposition<P>(&mut self, predicate: P) ->Option<usize>
where Self:Sized, P:FnMut(Self::Item) ->bool,

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:

leta = [1,2,3,4];letmutiter = a.into_iter();assert_eq!(iter.position(|x| x >=2),Some(1));// we can still use `iter`, as there are more elements.assert_eq!(iter.next(),Some(3));// The returned index depends on iterator stateassert_eq!(iter.position(|x| x ==4),Some(0));
1.0.0 ·Source

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:

leta = [-1,2,3,4];letmutiter = a.into_iter();assert_eq!(iter.rposition(|x| x >=2),Some(3));// we can still use `iter`, as there are more elements.assert_eq!(iter.next(),Some(-1));assert_eq!(iter.next_back(),Some(3));
1.0.0 ·Source

fnmax(self) ->Option<Self::Item>
where Self:Sized, Self::Item:Ord,

Returns the maximum element of an iterator.

If several elements are equally maximum, the last element isreturned. If the iterator is empty,None is returned.

Note thatf32/f64 doesn’t implementOrd due to NaN beingincomparable. You can work around this by usingIterator::reduce:

assert_eq!(    [2.4, f32::NAN,1.3]        .into_iter()        .reduce(f32::max)        .unwrap_or(0.),2.4);
§Examples
leta = [1,2,3];letb: [u32;0] = [];assert_eq!(a.into_iter().max(),Some(3));assert_eq!(b.into_iter().max(),None);
1.0.0 ·Source

fnmin(self) ->Option<Self::Item>
where Self:Sized, Self::Item:Ord,

Returns the minimum element of an iterator.

If several elements are equally minimum, the first element is returned.If the iterator is empty,None is returned.

Note thatf32/f64 doesn’t implementOrd due to NaN beingincomparable. You can work around this by usingIterator::reduce:

assert_eq!(    [2.4, f32::NAN,1.3]        .into_iter()        .reduce(f32::min)        .unwrap_or(0.),1.3);
§Examples
leta = [1,2,3];letb: [u32;0] = [];assert_eq!(a.into_iter().min(),Some(1));assert_eq!(b.into_iter().min(),None);
1.6.0 ·Source

fnmax_by_key<B, F>(self, f: F) ->Option<Self::Item>
where B:Ord, Self:Sized, F:FnMut(&Self::Item) -> B,

Returns the element that gives the maximum value from thespecified function.

If several elements are equally maximum, the last element isreturned. If the iterator is empty,None is returned.

§Examples
leta = [-3_i32,0,1,5, -10];assert_eq!(a.into_iter().max_by_key(|x| x.abs()).unwrap(), -10);
1.15.0 ·Source

fnmax_by<F>(self, compare: F) ->Option<Self::Item>
where Self:Sized, F:FnMut(&Self::Item, &Self::Item) ->Ordering,

Returns the element that gives the maximum value with respect to thespecified comparison function.

If several elements are equally maximum, the last element isreturned. If the iterator is empty,None is returned.

§Examples
leta = [-3_i32,0,1,5, -10];assert_eq!(a.into_iter().max_by(|x, y| x.cmp(y)).unwrap(),5);
1.6.0 ·Source

fnmin_by_key<B, F>(self, f: F) ->Option<Self::Item>
where B:Ord, Self:Sized, F:FnMut(&Self::Item) -> B,

Returns the element that gives the minimum value from thespecified function.

If several elements are equally minimum, the first element isreturned. If the iterator is empty,None is returned.

§Examples
leta = [-3_i32,0,1,5, -10];assert_eq!(a.into_iter().min_by_key(|x| x.abs()).unwrap(),0);
1.15.0 ·Source

fnmin_by<F>(self, compare: F) ->Option<Self::Item>
where Self:Sized, F:FnMut(&Self::Item, &Self::Item) ->Ordering,

Returns the element that gives the minimum value with respect to thespecified comparison function.

If several elements are equally minimum, the first element isreturned. If the iterator is empty,None is returned.

§Examples
leta = [-3_i32,0,1,5, -10];assert_eq!(a.into_iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
1.0.0 ·Source

fnrev(self) ->Rev<Self>

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
leta = [1,2,3];letmutiter = a.into_iter().rev();assert_eq!(iter.next(),Some(3));assert_eq!(iter.next(),Some(2));assert_eq!(iter.next(),Some(1));assert_eq!(iter.next(),None);
1.0.0 ·Source

fnunzip<A, B, FromA, FromB>(self) ->(FromA, FromB)
where FromA:Default +Extend<A>, FromB:Default +Extend<B>, Self:Sized +Iterator<Item =(A, B)>,

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 ·Source

fncopied<'a, T>(self) ->Copied<Self>
where T:Copy + 'a, Self:Sized +Iterator<Item =&'a T>,

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
leta = [1,2,3];letv_copied: Vec<_> = a.iter().copied().collect();// copied is the same as .map(|&x| x)letv_map: Vec<_> = a.iter().map(|&x| x).collect();assert_eq!(v_copied, [1,2,3]);assert_eq!(v_map, [1,2,3]);
1.0.0 ·Source

fncloned<'a, T>(self) ->Cloned<Self>
where T:Clone + 'a, Self:Sized +Iterator<Item =&'a T>,

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 ·Source

fncycle(self) ->Cycle<Self>
where Self:Sized +Clone,

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
leta = [1,2,3];letmutiter = a.into_iter().cycle();loop{assert_eq!(iter.next(),Some(1));assert_eq!(iter.next(),Some(2));assert_eq!(iter.next(),Some(3));}
Source

fnarray_chunks<const N:usize>(self) ->ArrayChunks<Self, N>
where Self:Sized,

🔬This is a nightly-only experimental API. (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:

#![feature(iter_array_chunks)]letmutiter ="lorem".chars().array_chunks();assert_eq!(iter.next(),Some(['l','o']));assert_eq!(iter.next(),Some(['r','e']));assert_eq!(iter.next(),None);assert_eq!(iter.into_remainder().as_slice(),&['m']);
#![feature(iter_array_chunks)]letdata = [1,1,2, -2,6,0,3,1];//          ^-----^  ^------^for[x, y, z]indata.iter().array_chunks() {assert_eq!(x + y + z,4);}
1.11.0 ·Source

fnsum<S>(self) -> S
where Self:Sized, S:Sum<Self::Item>,

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
leta = [1,2,3];letsum: i32 = a.iter().sum();assert_eq!(sum,6);letb: Vec<f32> =vec![];letsum: f32 = b.iter().sum();assert_eq!(sum, -0.0_f32);
1.11.0 ·Source

fnproduct<P>(self) -> P
where Self:Sized, P:Product<Self::Item>,

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
fnfactorial(n: u32) -> u32 {    (1..=n).product()}assert_eq!(factorial(0),1);assert_eq!(factorial(1),1);assert_eq!(factorial(5),120);
1.5.0 ·Source

fncmp<I>(self, other: I) ->Ordering
where I:IntoIterator<Item = Self::Item>, Self::Item:Ord, Self:Sized,

Lexicographically compares the elements of thisIterator with thoseof another.

§Examples
usestd::cmp::Ordering;assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);assert_eq!([1].iter().cmp([1,2].iter()), Ordering::Less);assert_eq!([1,2].iter().cmp([1].iter()), Ordering::Greater);
Source

fncmp_by<I, F>(self, other: I, cmp: F) ->Ordering
where Self:Sized, I:IntoIterator, F:FnMut(Self::Item, <I asIntoIterator>::Item) ->Ordering,

🔬This is a nightly-only experimental API. (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 ·Source

fnpartial_cmp<I>(self, other: I) ->Option<Ordering>
where I:IntoIterator, Self::Item:PartialOrd<<I asIntoIterator>::Item>, Self:Sized,

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:

assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()),None);

The results are determined by the order of evaluation.

usestd::cmp::Ordering;assert_eq!([1.0, f64::NAN].iter().partial_cmp([2.0, f64::NAN].iter()),Some(Ordering::Less));assert_eq!([2.0, f64::NAN].iter().partial_cmp([1.0, f64::NAN].iter()),Some(Ordering::Greater));assert_eq!([f64::NAN,1.0].iter().partial_cmp([f64::NAN,2.0].iter()),None);
Source

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>,

🔬This is a nightly-only experimental API. (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));
1.5.0 ·Source

fneq<I>(self, other: I) ->bool
where I:IntoIterator, Self::Item:PartialEq<<I asIntoIterator>::Item>, Self:Sized,

Determines if the elements of thisIterator are equal to those ofanother.

§Examples
assert_eq!([1].iter().eq([1].iter()),true);assert_eq!([1].iter().eq([1,2].iter()),false);
Source

fneq_by<I, F>(self, other: I, eq: F) ->bool
where Self:Sized, I:IntoIterator, F:FnMut(Self::Item, <I asIntoIterator>::Item) ->bool,

🔬This is a nightly-only experimental API. (iter_order_by #64295)

Determines if the elements of thisIterator are equal to those ofanother with respect to the specified equality function.

§Examples
#![feature(iter_order_by)]letxs = [1,2,3,4];letys = [1,4,9,16];assert!(xs.iter().eq_by(ys, |x, y| x * x == y));
1.5.0 ·Source

fnne<I>(self, other: I) ->bool
where I:IntoIterator, Self::Item:PartialEq<<I asIntoIterator>::Item>, Self:Sized,

Determines if the elements of thisIterator are not equal to those ofanother.

§Examples
assert_eq!([1].iter().ne([1].iter()),false);assert_eq!([1].iter().ne([1,2].iter()),true);
1.5.0 ·Source

fnlt<I>(self, other: I) ->bool
where I:IntoIterator, Self::Item:PartialOrd<<I asIntoIterator>::Item>, Self:Sized,

Determines if the elements of thisIterator arelexicographicallyless than those of another.

§Examples
assert_eq!([1].iter().lt([1].iter()),false);assert_eq!([1].iter().lt([1,2].iter()),true);assert_eq!([1,2].iter().lt([1].iter()),false);assert_eq!([1,2].iter().lt([1,2].iter()),false);
1.5.0 ·Source

fnle<I>(self, other: I) ->bool
where I:IntoIterator, Self::Item:PartialOrd<<I asIntoIterator>::Item>, Self:Sized,

Determines if the elements of thisIterator arelexicographicallyless or equal to those of another.

§Examples
assert_eq!([1].iter().le([1].iter()),true);assert_eq!([1].iter().le([1,2].iter()),true);assert_eq!([1,2].iter().le([1].iter()),false);assert_eq!([1,2].iter().le([1,2].iter()),true);
1.5.0 ·Source

fngt<I>(self, other: I) ->bool
where I:IntoIterator, Self::Item:PartialOrd<<I asIntoIterator>::Item>, Self:Sized,

Determines if the elements of thisIterator arelexicographicallygreater than those of another.

§Examples
assert_eq!([1].iter().gt([1].iter()),false);assert_eq!([1].iter().gt([1,2].iter()),false);assert_eq!([1,2].iter().gt([1].iter()),true);assert_eq!([1,2].iter().gt([1,2].iter()),false);
1.5.0 ·Source

fnge<I>(self, other: I) ->bool
where I:IntoIterator, Self::Item:PartialOrd<<I asIntoIterator>::Item>, Self:Sized,

Determines if the elements of thisIterator arelexicographicallygreater than or equal to those of another.

§Examples
assert_eq!([1].iter().ge([1].iter()),true);assert_eq!([1].iter().ge([1,2].iter()),false);assert_eq!([1,2].iter().ge([1].iter()),true);assert_eq!([1,2].iter().ge([1,2].iter()),true);
1.82.0 ·Source

fnis_sorted(self) ->bool
where Self:Sized, Self::Item:PartialOrd,

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
assert!([1,2,2,9].iter().is_sorted());assert!(![1,3,2,4].iter().is_sorted());assert!([0].iter().is_sorted());assert!(std::iter::empty::<i32>().is_sorted());assert!(![0.0,1.0, f32::NAN].iter().is_sorted());
1.82.0 ·Source

fnis_sorted_by<F>(self, compare: F) ->bool
where Self:Sized, F:FnMut(&Self::Item, &Self::Item) ->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 ·Source

fnis_sorted_by_key<F, K>(self, f: F) ->bool
where Self:Sized, F:FnMut(Self::Item) -> K, K:PartialOrd,

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
assert!(["c","bb","aaa"].iter().is_sorted_by_key(|s| s.len()));assert!(![-2i32, -1,0,3].iter().is_sorted_by_key(|n| n.abs()));

Implementors§

Source§

implIterator for core::ffi::c_str::Bytes<'_>

1.0.0 ·Source§

implIterator for std::ascii::EscapeDefault

1.20.0 ·Source§

implIterator for std::char::EscapeDebug

1.0.0 ·Source§

implIterator for std::char::EscapeDefault

1.0.0 ·Source§

implIterator for std::char::EscapeUnicode

1.0.0 ·Source§

implIterator forToLowercase

1.0.0 ·Source§

implIterator forToUppercase

1.0.0 ·Source§

implIterator forArgs

1.0.0 ·Source§

implIterator forArgsOs

1.0.0 ·Source§

implIterator forVars

1.0.0 ·Source§

implIterator forVarsOs

1.0.0 ·Source§

implIterator forReadDir

Source§

implIterator forIntoIncoming

1.0.0 ·Source§

implIterator forEncodeWide<'_>

Available onWindows only.
1.0.0 ·Source§

implIterator for std::str::Bytes<'_>

1.6.0 ·Source§

implIterator for std::string::Drain<'_>

Source§

implIterator forIntoChars

Source§

impl<'a>Iterator forSource<'a>

Source§

typeItem = &'a (dynError + 'static)

1.0.0 ·Source§

impl<'a>Iterator forSplitPaths<'a>

1.0.0 ·Source§

impl<'a>Iterator for std::net::Incoming<'a>

1.10.0 ·Source§

impl<'a>Iterator for std::os::unix::net::Incoming<'a>

Available onUnix only.
Source§

impl<'a>Iterator forMessages<'a>

Available on(Android or Linux or Cygwin) and Unix only.
Source§

impl<'a>Iterator forScmCredentials<'a>

Available on(Android or Linux or Cygwin) and Unix only.
Source§

impl<'a>Iterator forScmRights<'a>

Available on(Android or Linux or Cygwin) and Unix only.
1.28.0 ·Source§

impl<'a>Iterator forAncestors<'a>

1.0.0 ·Source§

impl<'a>Iterator forComponents<'a>

1.0.0 ·Source§

impl<'a>Iterator for std::path::Iter<'a>

1.57.0 ·Source§

impl<'a>Iterator forCommandArgs<'a>

1.57.0 ·Source§

impl<'a>Iterator forCommandEnvs<'a>

1.60.0 ·Source§

impl<'a>Iterator forEscapeAscii<'a>

1.0.0 ·Source§

impl<'a>Iterator forCharIndices<'a>

1.0.0 ·Source§

impl<'a>Iterator forChars<'a>

1.8.0 ·Source§

impl<'a>Iterator forEncodeUtf16<'a>

1.34.0 ·Source§

impl<'a>Iterator for std::str::EscapeDebug<'a>

1.34.0 ·Source§

impl<'a>Iterator for std::str::EscapeDefault<'a>

1.34.0 ·Source§

impl<'a>Iterator for std::str::EscapeUnicode<'a>

1.0.0 ·Source§

impl<'a>Iterator for std::str::Lines<'a>

Source§

typeItem = &'astr

1.0.0 ·Source§

impl<'a>Iterator forLinesAny<'a>

Source§

typeItem = &'astr

1.34.0 ·Source§

impl<'a>Iterator forSplitAsciiWhitespace<'a>

Source§

typeItem = &'astr

1.1.0 ·Source§

impl<'a>Iterator forSplitWhitespace<'a>

Source§

typeItem = &'astr

1.79.0 ·Source§

impl<'a>Iterator forUtf8Chunks<'a>

1.0.0 ·Source§

impl<'a, A>Iterator for std::option::Iter<'a, A>

1.0.0 ·Source§

impl<'a, A>Iterator for std::option::IterMut<'a, A>

1.80.0 ·Source§

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.

1.80.0 ·Source§

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.1.0 ·Source§

impl<'a, I, T>Iterator forCloned<I>
where T: 'a +Clone, I:Iterator<Item =&'a T>,

Source§

typeItem = T

1.36.0 ·Source§

impl<'a, I, T>Iterator forCopied<I>
where T: 'a +Copy, I:Iterator<Item =&'a T>,

Source§

typeItem = T

1.0.0 ·Source§

impl<'a, K>Iterator for std::collections::hash_set::Drain<'a, K>

Source§

typeItem = K

1.0.0 ·Source§

impl<'a, K>Iterator for std::collections::hash_set::Iter<'a, K>

1.0.0 ·Source§

impl<'a, K, V>Iterator for std::collections::btree_map::Iter<'a, K, V>
where K: 'a, V: 'a,

1.0.0 ·Source§

impl<'a, K, V>Iterator for std::collections::btree_map::IterMut<'a, K, V>

1.0.0 ·Source§

impl<'a, K, V>Iterator for std::collections::btree_map::Keys<'a, K, V>

1.17.0 ·Source§

impl<'a, K, V>Iterator for std::collections::btree_map::Range<'a, K, V>

1.17.0 ·Source§

impl<'a, K, V>Iterator forRangeMut<'a, K, V>

1.0.0 ·Source§

impl<'a, K, V>Iterator for std::collections::btree_map::Values<'a, K, V>

1.10.0 ·Source§

impl<'a, K, V>Iterator for std::collections::btree_map::ValuesMut<'a, K, V>

1.6.0 ·Source§

impl<'a, K, V>Iterator for std::collections::hash_map::Drain<'a, K, V>

1.0.0 ·Source§

impl<'a, K, V>Iterator for std::collections::hash_map::Iter<'a, K, V>

1.0.0 ·Source§

impl<'a, K, V>Iterator for std::collections::hash_map::IterMut<'a, K, V>

1.0.0 ·Source§

impl<'a, K, V>Iterator for std::collections::hash_map::Keys<'a, K, V>

1.0.0 ·Source§

impl<'a, K, V>Iterator for std::collections::hash_map::Values<'a, K, V>

1.10.0 ·Source§

impl<'a, K, V>Iterator for std::collections::hash_map::ValuesMut<'a, K, V>

1.5.0 ·Source§

impl<'a, P>Iterator forMatchIndices<'a, P>
where P:Pattern,

Source§

typeItem = (usize, &'astr)

1.2.0 ·Source§

impl<'a, P>Iterator forMatches<'a, P>
where P:Pattern,

Source§

typeItem = &'astr

1.5.0 ·Source§

impl<'a, P>Iterator forRMatchIndices<'a, P>
where P:Pattern, <P asPattern>::Searcher<'a>:ReverseSearcher<'a>,

Source§

typeItem = (usize, &'astr)

1.2.0 ·Source§

impl<'a, P>Iterator forRMatches<'a, P>
where P:Pattern, <P asPattern>::Searcher<'a>:ReverseSearcher<'a>,

Source§

typeItem = &'astr

1.0.0 ·Source§

impl<'a, P>Iterator for std::str::RSplit<'a, P>
where P:Pattern, <P asPattern>::Searcher<'a>:ReverseSearcher<'a>,

Source§

typeItem = &'astr

1.0.0 ·Source§

impl<'a, P>Iterator for std::str::RSplitN<'a, P>
where P:Pattern, <P asPattern>::Searcher<'a>:ReverseSearcher<'a>,

Source§

typeItem = &'astr

1.0.0 ·Source§

impl<'a, P>Iterator forRSplitTerminator<'a, P>
where P:Pattern, <P asPattern>::Searcher<'a>:ReverseSearcher<'a>,

Source§

typeItem = &'astr

1.0.0 ·Source§

impl<'a, P>Iterator for std::str::Split<'a, P>
where P:Pattern,

Source§

typeItem = &'astr

1.51.0 ·Source§

impl<'a, P>Iterator for std::str::SplitInclusive<'a, P>
where P:Pattern,

Source§

typeItem = &'astr

1.0.0 ·Source§

impl<'a, P>Iterator for std::str::SplitN<'a, P>
where P:Pattern,

Source§

typeItem = &'astr

1.0.0 ·Source§

impl<'a, P>Iterator forSplitTerminator<'a, P>
where P:Pattern,

Source§

typeItem = &'astr

1.0.0 ·Source§

impl<'a, T>Iterator for std::collections::binary_heap::Iter<'a, T>

1.0.0 ·Source§

impl<'a, T>Iterator for std::collections::btree_set::Iter<'a, T>

1.17.0 ·Source§

impl<'a, T>Iterator for std::collections::btree_set::Range<'a, T>

1.0.0 ·Source§

impl<'a, T>Iterator for std::collections::btree_set::SymmetricDifference<'a, T>
where T:Ord,

1.0.0 ·Source§

impl<'a, T>Iterator for std::collections::btree_set::Union<'a, T>
where T:Ord,

1.0.0 ·Source§

impl<'a, T>Iterator for std::collections::linked_list::Iter<'a, T>

1.0.0 ·Source§

impl<'a, T>Iterator for std::collections::linked_list::IterMut<'a, T>

1.0.0 ·Source§

impl<'a, T>Iterator for std::collections::vec_deque::Iter<'a, T>

1.0.0 ·Source§

impl<'a, T>Iterator for std::collections::vec_deque::IterMut<'a, T>

1.0.0 ·Source§

impl<'a, T>Iterator for std::result::Iter<'a, T>

1.0.0 ·Source§

impl<'a, T>Iterator for std::result::IterMut<'a, T>

1.0.0 ·Source§

impl<'a, T>Iterator forChunks<'a, T>

Source§

typeItem = &'a[T]

1.31.0 ·Source§

impl<'a, T>Iterator forChunksExact<'a, T>

Source§

typeItem = &'a[T]

1.31.0 ·Source§

impl<'a, T>Iterator forChunksExactMut<'a, T>

Source§

typeItem = &'a mut[T]

1.0.0 ·Source§

impl<'a, T>Iterator forChunksMut<'a, T>

Source§

typeItem = &'a mut[T]

1.0.0 ·Source§

impl<'a, T>Iterator for std::slice::Iter<'a, T>

1.0.0 ·Source§

impl<'a, T>Iterator for std::slice::IterMut<'a, T>

1.31.0 ·Source§

impl<'a, T>Iterator forRChunks<'a, T>

Source§

typeItem = &'a[T]

1.31.0 ·Source§

impl<'a, T>Iterator forRChunksExact<'a, T>

Source§

typeItem = &'a[T]

1.31.0 ·Source§

impl<'a, T>Iterator forRChunksExactMut<'a, T>

Source§

typeItem = &'a mut[T]

1.31.0 ·Source§

impl<'a, T>Iterator forRChunksMut<'a, T>

Source§

typeItem = &'a mut[T]

1.0.0 ·Source§

impl<'a, T>Iterator forWindows<'a, T>

Source§

typeItem = &'a[T]

Source§

impl<'a, T>Iterator for std::sync::mpmc::Iter<'a, T>

Source§

typeItem = T

Source§

impl<'a, T>Iterator for std::sync::mpmc::TryIter<'a, T>

Source§

typeItem = T

1.0.0 ·Source§

impl<'a, T>Iterator for std::sync::mpsc::Iter<'a, T>

Source§

typeItem = T

1.15.0 ·Source§

impl<'a, T>Iterator for std::sync::mpsc::TryIter<'a, T>

Source§

typeItem = T

1.0.0 ·Source§

impl<'a, T, A>Iterator for std::collections::btree_set::Difference<'a, T, A>
where T:Ord, A:Allocator +Clone,

1.0.0 ·Source§

impl<'a, T, A>Iterator for std::collections::btree_set::Intersection<'a, T, A>
where T:Ord, A:Allocator +Clone,

1.77.0 ·Source§

impl<'a, T, P>Iterator forChunkBy<'a, T, P>
where T: 'a, P:FnMut(&T,&T) ->bool,

Source§

typeItem = &'a[T]

1.77.0 ·Source§

impl<'a, T, P>Iterator forChunkByMut<'a, T, P>
where T: 'a, P:FnMut(&T,&T) ->bool,

Source§

typeItem = &'a mut[T]

1.27.0 ·Source§

impl<'a, T, P>Iterator for std::slice::RSplit<'a, T, P>
where P:FnMut(&T) ->bool,

Source§

typeItem = &'a[T]

1.27.0 ·Source§

impl<'a, T, P>Iterator forRSplitMut<'a, T, P>
where P:FnMut(&T) ->bool,

Source§

typeItem = &'a mut[T]

1.0.0 ·Source§

impl<'a, T, P>Iterator for std::slice::RSplitN<'a, T, P>
where P:FnMut(&T) ->bool,

Source§

typeItem = &'a[T]

1.0.0 ·Source§

impl<'a, T, P>Iterator forRSplitNMut<'a, T, P>
where P:FnMut(&T) ->bool,

Source§

typeItem = &'a mut[T]

1.0.0 ·Source§

impl<'a, T, P>Iterator for std::slice::Split<'a, T, P>
where P:FnMut(&T) ->bool,

Source§

typeItem = &'a[T]

1.51.0 ·Source§

impl<'a, T, P>Iterator for std::slice::SplitInclusive<'a, T, P>
where P:FnMut(&T) ->bool,

Source§

typeItem = &'a[T]

1.51.0 ·Source§

impl<'a, T, P>Iterator forSplitInclusiveMut<'a, T, P>
where P:FnMut(&T) ->bool,

Source§

typeItem = &'a mut[T]

1.0.0 ·Source§

impl<'a, T, P>Iterator forSplitMut<'a, T, P>
where P:FnMut(&T) ->bool,

Source§

typeItem = &'a mut[T]

1.0.0 ·Source§

impl<'a, T, P>Iterator for std::slice::SplitN<'a, T, P>
where P:FnMut(&T) ->bool,

Source§

typeItem = &'a[T]

1.0.0 ·Source§

impl<'a, T, P>Iterator forSplitNMut<'a, T, P>
where P:FnMut(&T) ->bool,

Source§

typeItem = &'a mut[T]

1.0.0 ·Source§

impl<'a, T, S>Iterator for std::collections::hash_set::Difference<'a, T, S>
where T:Eq +Hash, S:BuildHasher,

1.0.0 ·Source§

impl<'a, T, S>Iterator for std::collections::hash_set::Intersection<'a, T, S>
where T:Eq +Hash, S:BuildHasher,

1.0.0 ·Source§

impl<'a, T, S>Iterator for std::collections::hash_set::SymmetricDifference<'a, T, S>
where T:Eq +Hash, S:BuildHasher,

1.0.0 ·Source§

impl<'a, T, S>Iterator for std::collections::hash_set::Union<'a, T, S>
where T:Eq +Hash, S:BuildHasher,

Source§

impl<'a, T, const N:usize>Iterator forArrayWindows<'a, T, N>

1.0.0 ·Source§

impl<A>Iterator for std::ops::Range<A>
where A:Step,

Source§

typeItem = A

1.0.0 ·Source§

impl<A>Iterator forRangeFrom<A>
where A:Step,

Source§

typeItem = A

1.26.0 ·Source§

impl<A>Iterator forRangeInclusive<A>
where A:Step,

Source§

typeItem = A

1.0.0 ·Source§

impl<A>Iterator for std::option::IntoIter<A>

Source§

typeItem = A

Source§

impl<A>Iterator forRangeFromIter<A>
where A:Step,

Source§

typeItem = A

Source§

impl<A>Iterator forRangeInclusiveIter<A>
where A:Step,

Source§

typeItem = A

Source§

impl<A>Iterator forRangeIter<A>
where A:Step,

Source§

typeItem = A

1.0.0 ·Source§

impl<A>Iterator forRepeat<A>
where A:Clone,

Source§

typeItem = A

1.82.0 ·Source§

impl<A>Iterator forRepeatN<A>
where A:Clone,

Source§

typeItem = A

1.0.0 ·Source§

impl<A, B>Iterator forChain<A, B>
where A:Iterator, B:Iterator<Item = <A asIterator>::Item>,

1.0.0 ·Source§

impl<A, B>Iterator forZip<A, B>
where A:Iterator, B:Iterator,

Source§

typeItem = (<A asIterator>::Item, <B asIterator>::Item)

1.43.0 ·Source§

impl<A, F>Iterator forOnceWith<F>
where F:FnOnce() -> A,

Source§

typeItem = A

1.28.0 ·Source§

impl<A, F>Iterator forRepeatWith<F>
where F:FnMut() -> A,

Source§

typeItem = A

1.0.0 ·Source§

impl<B, I, F>Iterator forFilterMap<I, F>
where I:Iterator, F:FnMut(<I asIterator>::Item) ->Option<B>,

Source§

typeItem = B

1.0.0 ·Source§

impl<B, I, F>Iterator forMap<I, F>
where I:Iterator, F:FnMut(<I asIterator>::Item) -> B,

Source§

typeItem = B

1.57.0 ·Source§

impl<B, I, P>Iterator forMapWhile<I, P>
where I:Iterator, P:FnMut(<I asIterator>::Item) ->Option<B>,

Source§

typeItem = B

1.0.0 ·Source§

impl<B, I, St, F>Iterator forScan<I, St, F>
where I:Iterator, F:FnMut(&mut St, <I asIterator>::Item) ->Option<B>,

Source§

typeItem = B

1.0.0 ·Source§

impl<B:BufRead>Iterator for std::io::Lines<B>

1.0.0 ·Source§

impl<B:BufRead>Iterator for std::io::Split<B>

Source§

impl<G>Iterator forFromCoroutine<G>
where G:Coroutine<Return =()> +Unpin,

1.0.0 ·Source§

impl<I>Iterator for&mut I
where I:Iterator + ?Sized,

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>
where I:Iterator<Item =u16>,

Source§

impl<I>Iterator forByRefSized<'_, I>
where I:Iterator,

1.0.0 ·Source§

impl<I>Iterator forCycle<I>
where I:Clone +Iterator,

1.0.0 ·Source§

impl<I>Iterator forEnumerate<I>
where I:Iterator,

1.0.0 ·Source§

impl<I>Iterator forFuse<I>
where I:Iterator,

Source§

impl<I>Iterator forIntersperse<I>
where I:Iterator, <I asIterator>::Item:Clone,

1.0.0 ·Source§

impl<I>Iterator forPeekable<I>
where I:Iterator,

1.0.0 ·Source§

impl<I>Iterator forRev<I>

1.0.0 ·Source§

impl<I>Iterator forSkip<I>
where I:Iterator,

1.28.0 ·Source§

impl<I>Iterator forStepBy<I>
where I:Iterator,

1.0.0 ·Source§

impl<I>Iterator forTake<I>
where I:Iterator,

1.80.0 ·Source§

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.

1.0.0 ·Source§

impl<I, A>Iterator forBox<I, A>
where I:Iterator + ?Sized, A:Allocator,

1.21.0 ·Source§

impl<I, A>Iterator forSplice<'_, I, A>
where I:Iterator, A:Allocator,

1.0.0 ·Source§

impl<I, F>Iterator forInspect<I, F>
where I:Iterator, F:FnMut(&<I asIterator>::Item),

Source§

impl<I, F, R, const N:usize>Iterator forMapWindows<I, F, N>
where I:Iterator, F:FnMut(&[<I asIterator>::Item;N]) -> R,

Source§

typeItem = R

Source§

impl<I, G>Iterator forIntersperseWith<I, G>
where I:Iterator, G:FnMut() -> <I asIterator>::Item,

1.0.0 ·Source§

impl<I, P>Iterator forFilter<I, P>
where I:Iterator, P:FnMut(&<I asIterator>::Item) ->bool,

1.0.0 ·Source§

impl<I, P>Iterator forSkipWhile<I, P>
where I:Iterator, P:FnMut(&<I asIterator>::Item) ->bool,

1.0.0 ·Source§

impl<I, P>Iterator forTakeWhile<I, P>
where I:Iterator, P:FnMut(&<I asIterator>::Item) ->bool,

1.29.0 ·Source§

impl<I, U>Iterator forFlatten<I>
where I:Iterator, <I asIterator>::Item:IntoIterator<IntoIter = U, Item = <U asIterator>::Item>, U:Iterator,

1.0.0 ·Source§

impl<I, U, F>Iterator forFlatMap<I, U, F>
where I:Iterator, U:IntoIterator, F:FnMut(<I asIterator>::Item) -> U,

Source§

impl<I, const N:usize>Iterator forArrayChunks<I, N>
where I:Iterator,

Source§

typeItem = [<I asIterator>::Item;N]

1.0.0 ·Source§

impl<K>Iterator for std::collections::hash_set::IntoIter<K>

Source§

typeItem = K

1.88.0 ·Source§

impl<K, F>Iterator for std::collections::hash_set::ExtractIf<'_, K, F>
where F:FnMut(&K) ->bool,

Source§

typeItem = K

1.0.0 ·Source§

impl<K, V>Iterator for std::collections::hash_map::IntoIter<K, V>

1.54.0 ·Source§

impl<K, V>Iterator for std::collections::hash_map::IntoKeys<K, V>

Source§

typeItem = K

1.54.0 ·Source§

impl<K, V>Iterator for std::collections::hash_map::IntoValues<K, V>

Source§

typeItem = V

1.0.0 ·Source§

impl<K, V, A>Iterator for std::collections::btree_map::IntoIter<K, V, A>
where A:Allocator +Clone,

1.54.0 ·Source§

impl<K, V, A>Iterator for std::collections::btree_map::IntoKeys<K, V, A>
where A:Allocator +Clone,

Source§

typeItem = K

1.54.0 ·Source§

impl<K, V, A>Iterator for std::collections::btree_map::IntoValues<K, V, A>
where A:Allocator +Clone,

Source§

typeItem = V

1.88.0 ·Source§

impl<K, V, F>Iterator for std::collections::hash_map::ExtractIf<'_, K, V, F>
where F:FnMut(&K,&mut V) ->bool,

1.91.0 ·Source§

impl<K, V, R, F, A>Iterator for std::collections::btree_map::ExtractIf<'_, K, V, R, F, A>

1.0.0 ·Source§

impl<R:Read>Iterator for std::io::Bytes<R>

1.80.0 ·Source§

impl<T> !Iterator for[T]

1.0.0 ·Source§

impl<T>Iterator for std::result::IntoIter<T>

Source§

typeItem = T

Source§

impl<T>Iterator for std::sync::mpmc::IntoIter<T>

Source§

typeItem = T

1.1.0 ·Source§

impl<T>Iterator for std::sync::mpsc::IntoIter<T>

Source§

typeItem = T

1.2.0 ·Source§

impl<T>Iterator forEmpty<T>

Source§

typeItem = T

1.2.0 ·Source§

impl<T>Iterator forOnce<T>

Source§

typeItem = T

1.6.0 ·Source§

impl<T, A>Iterator for std::collections::binary_heap::Drain<'_, T, A>
where A:Allocator,

Source§

typeItem = T

Source§

impl<T, A>Iterator forDrainSorted<'_, T, A>
where T:Ord, A:Allocator,

Source§

typeItem = T

1.0.0 ·Source§

impl<T, A>Iterator for std::collections::binary_heap::IntoIter<T, A>
where A:Allocator,

Source§

typeItem = T

Source§

impl<T, A>Iterator forIntoIterSorted<T, A>
where T:Ord, A:Allocator,

Source§

typeItem = T

1.0.0 ·Source§

impl<T, A>Iterator for std::collections::btree_set::IntoIter<T, A>
where A:Allocator +Clone,

Source§

typeItem = T

1.0.0 ·Source§

impl<T, A>Iterator for std::collections::linked_list::IntoIter<T, A>
where A:Allocator,

Source§

typeItem = T

1.6.0 ·Source§

impl<T, A>Iterator for std::collections::vec_deque::Drain<'_, T, A>
where A:Allocator,

Source§

typeItem = T

1.0.0 ·Source§

impl<T, A>Iterator for std::collections::vec_deque::IntoIter<T, A>
where A:Allocator,

Source§

typeItem = T

1.6.0 ·Source§

impl<T, A>Iterator for std::vec::Drain<'_, T, A>
where A:Allocator,

Source§

typeItem = T

1.0.0 ·Source§

impl<T, A>Iterator for std::vec::IntoIter<T, A>
where A:Allocator,

Source§

typeItem = T

1.34.0 ·Source§

impl<T, F>Iterator forFromFn<F>
where F:FnMut() ->Option<T>,

Source§

typeItem = T

1.34.0 ·Source§

impl<T, F>Iterator forSuccessors<T, F>
where F:FnMut(&T) ->Option<T>,

Source§

typeItem = T

1.87.0 ·Source§

impl<T, F, A>Iterator for std::collections::linked_list::ExtractIf<'_, T, F, A>
where A:Allocator, F:FnMut(&mut T) ->bool,

Source§

typeItem = T

Source§

impl<T, F, A>Iterator for std::collections::vec_deque::ExtractIf<'_, T, F, A>
where A:Allocator, F:FnMut(&mut T) ->bool,

Source§

typeItem = T

1.87.0 ·Source§

impl<T, F, A>Iterator for std::vec::ExtractIf<'_, T, F, A>
where A:Allocator, F:FnMut(&mut T) ->bool,

Source§

typeItem = T

1.91.0 ·Source§

impl<T, R, F, A>Iterator for std::collections::btree_set::ExtractIf<'_, T, R, F, A>
where A:Allocator +Clone, T:PartialOrd, R:RangeBounds<T>, F:FnMut(&T) ->bool,

Source§

typeItem = T

1.40.0 ·Source§

impl<T, const N:usize>Iterator for std::array::IntoIter<T, N>

Source§

typeItem = T


[8]ページ先頭

©2009-2026 Movatter.jp