Trait Iterator
trait Iterator
A trait for dealing with iterators.
This is the main iterator trait. For more about the concept of iterators
generally, please see the module-level documentation. In particular, you
may want to know how to implement Iterator.
Associated Types
type ItemThe type of the elements being iterated over.
Required Methods
fn next(self: &mut Self) -> Option<<Self as >::Item>Advances the iterator and returns the next value.
Returns
Nonewhen iteration is finished. Individual iterator implementations may choose to resume iteration, and so callingnext()again may or may not eventually start returningSome(Item)again at some point.Examples
let a = ; let mut iter = a.into_iter; // A call to next() returns the next value... assert_eq!; assert_eq!; assert_eq!; // ... and then None once it's over. assert_eq!; // More calls may or may not return `None`. Here, they always will. assert_eq!; assert_eq!;
Provided Methods
fn next_chunk<N: usize>(self: &mut Self) -> Result<[<Self as >::Item; N], IntoIter<<Self as >::Item, N>> where Self: SizedAdvances the iterator and returns an array containing the next
Nvalues.If there are not enough elements to fill the array then
Erris returned containing an iterator over the remaining elements.Examples
Basic usage:
let mut iter = "lorem".chars; assert_eq!; // N is inferred as 2 assert_eq!; // N is inferred as 3 assert_eq!; // N is explicitly 4Split a string and get the first three items.
let quote = "not all those who wander are lost"; let = quote.split_whitespace.next_chunk.unwrap; assert_eq!; assert_eq!; assert_eq!;fn size_hint(self: &Self) -> (usize, Option<usize>)Returns the bounds on the remaining length of the iterator.
Specifically,
size_hint()returns a tuple where the first element is the lower bound, and the second element is the upper bound.The second half of the tuple that is returned is an
[Option]<[usize]>. ANonehere means that either there is no known upper bound, or the upper bound is larger thanusize.Implementation notes
It is not enforced that an iterator implementation yields the declared number of elements. A buggy iterator may yield less than the lower bound or more than the upper bound of elements.
size_hint()is primarily intended to be used for optimizations such as reserving space for the elements of the iterator, but must not be trusted to e.g., omit bounds checks in unsafe code. An incorrect implementation ofsize_hint()should not lead to memory safety violations.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 any iterator.Examples
Basic usage:
let a = ; let mut iter = a.iter; assert_eq!; let _ = iter.next; assert_eq!;A more complex example:
// The even numbers in the range of zero to nine. let iter = .filter; // We might iterate from zero to ten times. Knowing that it's five // exactly wouldn't be possible without executing filter(). assert_eq!; // Let's add five more numbers with chain() let iter = .filter.chain; // now both bounds are increased by five assert_eq!;Returning
Nonefor an upper bound:// an infinite iterator has no upper bound // and the maximum possible lower bound let iter = 0..; assert_eq!;fn count(self: Self) -> usize where Self: SizedConsumes the iterator, counting the number of iterations and returning it.
This method will call
nextrepeatedly untilNoneis encountered, returning the number of times it sawSome. Note thatnexthas to be called at least once even if the iterator does not have any elements.Overflow Behavior
The method does no guarding against overflows, so counting elements of an iterator with more than
usize::MAXelements either produces the wrong result or panics. If overflow checks are enabled, a panic is guaranteed.Panics
This function might panic if the iterator has more than
usize::MAXelements.Examples
let a = ; assert_eq!; let a = ; assert_eq!;fn last(self: Self) -> Option<<Self as >::Item> where Self: SizedConsumes the iterator, returning the last element.
This method will evaluate the iterator until it returns
None. While doing so, it keeps track of the current element. AfterNoneis returned,last()will then return the last element it saw.Panics
This function might panic if the iterator is infinite.
Examples
let a = ; assert_eq!; let a = ; assert_eq!;fn advance_by(self: &mut Self, n: usize) -> Result<(), NonZero<usize>>Advances the iterator by
nelements.This method will eagerly skip
nelements by callingnextup tontimes untilNoneis encountered.advance_by(n)will returnOk(())if the iterator successfully advances bynelements, or aErr(NonZero<usize>)with valuekifNoneis encountered, wherekis remaining number of steps that could not be advanced because the iterator ran out. Ifselfis empty andnis non-zero, then this returnsErr(n). Otherwise,kis always less thann.Calling
advance_by(0)can do meaningful work, for exampleFlattencan advance its outer iterator until it finds an inner iterator that is not empty, which then often allows it to return a more accuratesize_hint()than in its initial state.Examples
use NonZero; let a = ; let mut iter = a.into_iter; assert_eq!; assert_eq!; assert_eq!; assert_eq!; // only `4` was skippedfn nth(self: &mut Self, n: usize) -> Option<<Self as >::Item>Returns the
nth element of the iterator.Like most indexing operations, the count starts from zero, so
nth(0)returns the first value,nth(1)the second, and so on.Note that all preceding elements, as well as the returned element, will be consumed from the iterator. That means that the preceding elements will be discarded, and also that calling
nth(0)multiple times on the same iterator will return different elements.nth()will returnNoneifnis greater than or equal to the length of the iterator.Examples
Basic usage:
let a = ; assert_eq!;Calling
nth()multiple times doesn't rewind the iterator:let a = ; let mut iter = a.into_iter; assert_eq!; assert_eq!;Returning
Noneif there are less thann + 1elements:let a = ; assert_eq!;fn step_by(self: Self, step: usize) -> StepBy<Self> where Self: SizedCreates an iterator starting at the same point, but stepping by the 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.
StepBybehaves 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_firstis the equivalent of:Panics
The method will panic if the given step is
0.Examples
let a = ; let mut iter = a.into_iter.step_by; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn chain<U>(self: Self, other: U) -> Chain<Self, <U as >::IntoIter> where Self: Sized, U: IntoIterator<Item = <Self as >::Item>Takes two iterators and creates a new iterator over both in sequence.
chain()will return a new iterator which will first iterate over values from the first iterator and then over values from the second iterator.In other words, it links two iterators together, in a chain. 🔗
onceis commonly used to adapt a single value into a chain of other kinds of iteration.Examples
Basic usage:
let s1 = "abc".chars; let s2 = "def".chars; let mut iter = s1.chain; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!;Since the argument to
chain()usesIntoIterator, we can pass anything that can be converted into anIterator, not just anIteratoritself. For example, arrays ([T]) implementIntoIterator, and so can be passed tochain()directly:let a1 = ; let a2 = ; let mut iter = a1.into_iter.chain; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!;If you work with Windows API, you may wish to convert
OsStrtoVec<u16>:fn zip<U>(self: Self, other: U) -> Zip<Self, <U as >::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 other iterators, returning a tuple where the first element comes from the first 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 returns
None,nextfrom the zipped iterator will returnNone. If the zipped iterator has no more elements to return then each further attempt to advance it will first try to advance the first iterator at most one time and if it still yielded an item try to advance the second iterator at most one time.To 'undo' the result of zipping up two iterators, see
unzip.Examples
Basic usage:
let s1 = "abc".chars; let s2 = "def".chars; let mut iter = s1.zip; assert_eq!; assert_eq!; assert_eq!; assert_eq!;Since the argument to
zip()usesIntoIterator, we can pass anything that can be converted into anIterator, not just anIteratoritself. For example, arrays ([T]) implementIntoIterator, and so can be passed tozip()directly:let a1 = ; let a2 = ; let mut iter = a1.into_iter.zip; assert_eq!; assert_eq!; assert_eq!; assert_eq!;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:let enumerate: = "foo".chars.enumerate.collect; let zipper: = .zip.collect; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!;If both iterators have roughly equivalent syntax, it may be more readable to use
zip:use zip; let a = ; let b = ; let mut zipped = zip; assert_eq!; assert_eq!; assert_eq!;compared to:
# let a = ; # let b = ; # let mut zipped = a .into_iter .map .skip .zip; # # assert_eq!; # assert_eq!; # assert_eq!;fn intersperse(self: Self, separator: <Self as >::Item) -> Intersperse<Self> where Self: Sized, <Self as >::Item: CloneCreates a new iterator which places a copy of
separatorbetween adjacent items of the original iterator.In case
separatordoes not implementCloneor needs to be computed every time, useintersperse_with.Examples
Basic usage:
let mut a = .into_iter.intersperse; assert_eq!; // The first element from `a`. assert_eq!; // The separator. assert_eq!; // The next element from `a`. assert_eq!; // The separator. assert_eq!; // The last element from `a`. assert_eq!; // The iterator is finished.interspersecan be very useful to join an iterator's items using a common element:let words = ; let hello: String = words.into_iter.intersperse.collect; assert_eq!;fn intersperse_with<G>(self: Self, separator: G) -> IntersperseWith<Self, G> where Self: Sized, G: FnMut() -> <Self as >::ItemCreates a new iterator which places an item generated by
separatorbetween adjacent items of the original iterator.The closure will be called exactly once each time an item is placed between two adjacent items from the underlying iterator; specifically, the closure is not called if the underlying iterator yields less than two items and after the last item is yielded.
If the iterator's item implements
Clone, it may be easier to useintersperse.Examples
Basic usage:
; let v = ; let mut it = v.into_iter.intersperse_with; assert_eq!; // The first element from `v`. assert_eq!; // The separator. assert_eq!; // The next element from `v`. assert_eq!; // The separator. assert_eq!; // The last element from `v`. assert_eq!; // The iterator is finished.intersperse_withcan be used in situations where the separator needs to be computed:let src = .iter.copied; // The closure mutably borrows its context to generate an item. let mut happy_emojis = .into_iter; let separator = ; let result = src.intersperse_with.; assert_eq!;fn map<B, F>(self: Self, f: F) -> Map<Self, F> where Self: Sized, F: FnMut(<Self as >::Item) -> BTakes a closure and creates an iterator which calls that closure on each element.
map()transforms one iterator into another, by means of its argument: something that implementsFnMut. It produces a new iterator which calls this closure on each element of the original iterator.If you are good at thinking in types, you can think of
map()like this: If you have an iterator that gives you elements of some typeA, and you want an iterator of some other typeB, you can usemap(), passing a closure that takes anAand returns aB.map()is conceptually similar to aforloop. However, asmap()is lazy, 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 considered more idiomatic to useforthanmap().Examples
Basic usage:
let a = ; let mut iter = a.iter.map; assert_eq!; assert_eq!; assert_eq!; assert_eq!;If you're doing some sort of side effect, prefer
fortomap():# // don't do this: .map; // it won't even execute, as it is lazy. Rust will warn you about this. // Instead, use a for-loop: for x in 0..5fn for_each<F>(self: Self, f: F) where Self: Sized, F: FnMut(<Self as >::Item)Calls a closure on each element of an iterator.
This is equivalent to using a
forloop on the iterator, althoughbreakandcontinueare not possible from a closure. It's generally more idiomatic to use aforloop, butfor_eachmay be more legible when processing items at the end of longer iterator chains. In some casesfor_eachmay also be faster than a loop, because it will use internal iteration on adapters likeChain.Examples
Basic usage:
use channel; let = channel; .map .for_each; let v: = rx.iter.collect; assert_eq!;For such a small example, a
forloop may be cleaner, butfor_eachmight be preferable to keep a functional style with longer iterators:.flat_map .enumerate .filter .for_each;fn filter<P>(self: Self, predicate: P) -> Filter<Self, P> where Self: Sized, P: FnMut(&<Self as >::Item) -> boolCreates an iterator which uses a closure to determine if an element should be yielded.
Given an element the closure must return
trueorfalse. The returned iterator will yield only the elements for which the closure returnstrue.Examples
Basic usage:
let a = ; let mut iter = a.into_iter.filter; assert_eq!; assert_eq!; assert_eq!;Because the closure passed to
filter()takes a reference, and many iterators iterate over references, this leads to a possibly confusing situation, where the type of the closure is a double reference:let s = &; let mut iter = s.iter.filter; // needs two *s! assert_eq!; assert_eq!;It's common to instead use destructuring on the argument to strip away one:
let s = &; let mut iter = s.iter.filter; // both & and * assert_eq!; assert_eq!;or both:
let s = &; let mut iter = s.iter.filter; // two &s assert_eq!; assert_eq!;of these layers.
Note that
iter.filter(f).next()is equivalent toiter.find(f).fn filter_map<B, F>(self: Self, f: F) -> FilterMap<Self, F> where Self: Sized, F: FnMut(<Self as >::Item) -> Option<B>Creates an iterator that both filters and maps.
The returned iterator yields only the
values for which the supplied closure returnsSome(value).filter_mapcan be used to make chains offilterandmapmore concise. The example below shows how amap().filter().map()can be shortened to a single call tofilter_map.Examples
Basic usage:
let a = ; let mut iter = a.iter.filter_map; assert_eq!; assert_eq!; assert_eq!;Here's the same example, but with
filterandmap:let a = ; let mut iter = a.iter.map.filter.map; assert_eq!; assert_eq!; assert_eq!;fn enumerate(self: Self) -> Enumerate<Self> where Self: SizedCreates an iterator which gives the current iteration count as well as the next value.
The iterator returned yields pairs
(i, val), whereiis the current index of iteration andvalis the value returned by the iterator.enumerate()keeps its count as ausize. If you want to count by a different sized integer, thezipfunction provides similar functionality.Overflow Behavior
The method does no guarding against overflows, so enumerating more than
usize::MAXelements either produces the wrong result or panics. If overflow checks are enabled, a panic is guaranteed.Panics
The returned iterator might panic if the to-be-returned index would overflow a
usize.Examples
let a = ; let mut iter = a.into_iter.enumerate; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn peekable(self: Self) -> Peekable<Self> where Self: SizedCreates an iterator which can use the
peekandpeek_mutmethods to look at the next element of the iterator without consuming it. See their documentation for more information.Note that the underlying iterator is still advanced when
peekorpeek_mutare called for the first time: In order to retrieve the next element,nextis called on the underlying iterator, hence any side effects (i.e. anything other than fetching the next value) of thenextmethod will occur.Examples
Basic usage:
let xs = ; let mut iter = xs.into_iter.peekable; // peek() lets us see into the future assert_eq!; assert_eq!; assert_eq!; // we can peek() multiple times, the iterator won't advance assert_eq!; assert_eq!; assert_eq!; // after the iterator is finished, so is peek() assert_eq!; assert_eq!;Using
peek_mutto mutate the next item without advancing the iterator:let xs = ; let mut iter = xs.into_iter.peekable; // `peek_mut()` lets us see into the future assert_eq!; assert_eq!; assert_eq!; if let Some = iter.peek_mut // The value reappears as the iterator continues assert_eq!;fn skip_while<P>(self: Self, predicate: P) -> SkipWhile<Self, P> where Self: Sized, P: FnMut(&<Self as >::Item) -> boolCreates an iterator that
skips elements based on a predicate.skip_while()takes a closure as an argument. It will call this closure on each element of the iterator, and ignore elements until it returnsfalse.After
falseis returned,skip_while()'s job is over, and the rest of the elements are yielded.Examples
Basic usage:
let a = ; let mut iter = a.into_iter.skip_while; assert_eq!; assert_eq!; assert_eq!;Because the closure passed to
skip_while()takes a reference, and many iterators iterate over references, this leads to a possibly confusing situation, where the type of the closure argument is a double reference:let s = &; let mut iter = s.iter.skip_while; // need two *s! assert_eq!; assert_eq!; assert_eq!;Stopping after an initial
false:let a = ; let mut iter = a.into_iter.skip_while; assert_eq!; assert_eq!; // while this would have been false, since we already got a false, // skip_while() isn't used any more assert_eq!; assert_eq!;fn take_while<P>(self: Self, predicate: P) -> TakeWhile<Self, P> where Self: Sized, P: FnMut(&<Self as >::Item) -> boolCreates an iterator that yields elements based on a predicate.
take_while()takes a closure as an argument. It will call this closure on each element of the iterator, and yield elements while it returnstrue.After
falseis returned,take_while()'s job is over, and the rest of the elements are ignored.Examples
Basic usage:
let a = ; let mut iter = a.into_iter.take_while; assert_eq!; assert_eq!;Because the closure passed to
take_while()takes a reference, and many iterators iterate over references, this leads to a possibly confusing situation, where the type of the closure is a double reference:let s = &; let mut iter = s.iter.take_while; // need two *s! assert_eq!; assert_eq!;Stopping after an initial
false:let a = ; let mut iter = a.into_iter.take_while; assert_eq!; // We have more elements that are less than zero, but since we already // got a false, take_while() ignores the remaining elements. assert_eq!;Because
take_while()needs to look at the value in order to see if it should be included or not, consuming iterators will see that it is removed:let a = ; let mut iter = a.into_iter; let result: = iter.by_ref.take_while.collect; assert_eq!; let result: = iter.collect; assert_eq!;The
3is no longer there, because it was consumed in order to see if the iteration should stop, but wasn't placed back into the iterator.fn map_while<B, P>(self: Self, predicate: P) -> MapWhile<Self, P> where Self: Sized, P: FnMut(<Self as >::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 this closure on each element of the iterator, and yield elements while it returns [Some(_)]Some.Examples
Basic usage:
let a = ; let mut iter = a.into_iter.map_while; assert_eq!; assert_eq!; assert_eq!;Here's the same example, but with
take_whileandmap:let a = ; let mut iter = a.into_iter .map .take_while .map; assert_eq!; assert_eq!; assert_eq!;Stopping after an initial [
None]:let a = ; let iter = a.into_iter.map_while; let 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!;Because
map_while()needs to look at the value in order to see if it should be included or not, consuming iterators will see that it is removed:let a = ; let mut iter = a.into_iter; let result: = iter.by_ref .map_while .collect; assert_eq!; let result: = iter.collect; assert_eq!;The
-3is no longer there, because it was consumed in order to see if the iteration should stop, but wasn't placed back into the iterator.Note that unlike
take_whilethis iterator is not fused. It is also not specified what this iterator returns after the firstNoneis returned. If you need a fused iterator, usefuse.fn skip(self: Self, n: usize) -> Skip<Self> where Self: SizedCreates an iterator that skips the first
nelements.skip(n)skips elements untilnelements are skipped or the end of the iterator is reached (whichever happens first). After that, all the remaining elements 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 the
nthmethod.Examples
let a = ; let mut iter = a.into_iter.skip; assert_eq!; assert_eq!;fn take(self: Self, n: usize) -> Take<Self> where Self: SizedCreates an iterator that yields the first
nelements, or fewer if the underlying iterator ends sooner.take(n)yields elements untilnelements are yielded or the end of the iterator is reached (whichever happens first). The returned iterator is a prefix of lengthnif the original iterator contains at leastnelements, otherwise it contains all of the (fewer thann) elements of the original iterator.Examples
Basic usage:
let a = ; let mut iter = a.into_iter.take; assert_eq!; assert_eq!; assert_eq!;take()is often used with an infinite iterator, to make it finite:let mut iter = .take; assert_eq!; assert_eq!; assert_eq!; assert_eq!;If less than
nelements are available,takewill limit itself to the size of the underlying iterator:let v = ; let mut iter = v.into_iter.take; assert_eq!; assert_eq!; assert_eq!;Use
by_refto take from the iterator without consuming it, and then continue using the original iterator:let mut words = .into_iter; // Take the first two words. let hello_world: = words.by_ref.take.collect; assert_eq!; // Collect the rest of the words. // We can only do this because we used `by_ref` earlier. let of_rust: = words.collect; assert_eq!;fn scan<St, B, F>(self: Self, initial_state: St, f: F) -> Scan<Self, St, F> where Self: Sized, F: FnMut(&mut St, <Self as >::Item) -> Option<B>An iterator adapter which, like
fold, holds internal state, but unlikefold, produces a new iterator.scan()takes two arguments: an initial value which seeds the internal state, and a closure with two arguments, the first being a mutable reference to the internal state and the second an iterator element. The closure can assign to the internal state to share state between iterations.On iteration, the closure will be applied to each element of the iterator and the return value from the closure, an
Option, is returned by thenextmethod. Thus the closure can returnSome(value)to yieldvalue, orNoneto end the iteration.Examples
let a = ; let mut iter = a.into_iter.scan; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn flat_map<U, F>(self: Self, f: F) -> FlatMap<Self, U, F> where Self: Sized, U: IntoIterator, F: FnMut(<Self as >::Item) -> UCreates an iterator that works like map, but flattens nested structure.
The
mapadapter is very useful, but only when the closure argument produces values. If it produces an iterator instead, there's an extra layer of indirection.flat_map()will remove this extra layer on its own.You can think of
flat_map(f)as the semantic equivalent ofmapping, and thenflattening as inmap(f).flatten().Another way of thinking about
flat_map():map's closure returns one item for each element, andflat_map()'s closure returns an iterator for each element.Examples
let words = ; // chars() returns an iterator let merged: String = words.iter .flat_map .collect; assert_eq!;fn flatten(self: Self) -> Flatten<Self> where Self: Sized, <Self as >::Item: IntoIteratorCreates an iterator that flattens nested structure.
This is useful when you have an iterator of iterators or an iterator of things that can be turned into iterators and you want to remove one level of indirection.
Examples
Basic usage:
let data = vec!; let flattened: = data.into_iter.flatten.collect; assert_eq!;Mapping and then flattening:
let words = ; // chars() returns an iterator let merged: String = words.iter .map .flatten .collect; assert_eq!;You can also rewrite this in terms of
flat_map(), which is preferable in this case since it conveys intent more clearly:let words = ; // chars() returns an iterator let merged: String = words.iter .flat_map .collect; assert_eq!;Flattening works on any
IntoIteratortype, includingOptionandResult:let options = vec!; let flattened_options: = options.into_iter.flatten.collect; assert_eq!; let results = vec!; let flattened_results: = results.into_iter.flatten.collect; assert_eq!;Flattening only removes one level of nesting at a time:
let d3 = ; let d2: = d3.into_iter.flatten.collect; assert_eq!; let d1: = d3.into_iter.flatten.flatten.collect; assert_eq!;Here we see that
flatten()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 be two-dimensional and not one-dimensional. To get a one-dimensional structure, you have toflatten()again.fn map_windows<F, R, N: usize>(self: Self, f: F) -> MapWindows<Self, F, N> where Self: Sized, F: FnMut(&[<Self as >::Item; N]) -> RCalls the given function
ffor each contiguous window of sizeNoverselfand 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 the arguments
&['a', 'b'],&['b', 'c']and&['c', 'd']respectively.let strings = "abcd".chars .map_windows .; assert_eq!;Note that the const parameter
Nis usually inferred by the destructured argument in the closure.The returned iterator yields 𝑘 −
N+ 1 items (where 𝑘 is the number of items yielded byself). If 𝑘 is less thanN, this method yields an empty iterator.The returned iterator implements
FusedIterator, 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 iterator should be fused.Panics
Panics if
Nis zero. This check will most probably get changed to a compile time error before this method gets stabilized.#![feature(iter_map_windows)] let iter = std::iter::repeat(0).map_windows(|&[]| ());Examples
Building the sums of neighboring numbers.
let mut it = .iter.map_windows; assert_eq!; // 1 + 3 assert_eq!; // 3 + 8 assert_eq!; // 8 + 1 assert_eq!;Since the elements in the following example implement
Copy, we can just copy the array and get an iterator over the windows.let mut it = "ferris".chars.map_windows; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!;You can also use this function to check the sortedness of an iterator. For the simple case, rather use
Iterator::is_sorted.let mut it = .iter .map_windows; assert_eq!; // 0.5 <= 1.0 assert_eq!; // 1.0 <= 3.5 assert_eq!; // 3.5 <= 3.0 assert_eq!; // 3.0 <= 8.5 assert_eq!; // 8.5 <= 8.5 assert_eq!; // 8.5 <= NAN assert_eq!;For non-fused iterators, they are fused after
map_windows.let mut iter = default; // yields 0..5 first. assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; // then we can see our iterator going back and forth assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; // however, with `.map_windows()`, it is fused. let mut iter = default .map_windows; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; // it will always return `None` after the first time. assert_eq!; assert_eq!; assert_eq!;fn fuse(self: Self) -> Fuse<Self> where Self: SizedCreates an iterator which ends after the first
None.After an iterator returns
None, future calls may or may not yieldSome(T)again.fuse()adapts an iterator, ensuring that after aNoneis given, it will always returnNoneforever.Note that the
Fusewrapper is a no-op on iterators that implement theFusedIteratortrait.fuse()may therefore behave incorrectly if theFusedIteratortrait is improperly implemented.Examples
// an iterator which alternates between Some and None let mut iter = Alternate ; // we can see our iterator going back and forth assert_eq!; assert_eq!; assert_eq!; assert_eq!; // however, once we fuse it... let mut iter = iter.fuse; assert_eq!; assert_eq!; // it will always return `None` after the first time. assert_eq!; assert_eq!; assert_eq!;fn inspect<F>(self: Self, f: F) -> Inspect<Self, F> where Self: Sized, F: FnMut(&<Self as >::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's happening at various parts in the pipeline. To do that, insert a call to
inspect().It's more common for
inspect()to be used as a debugging tool than to exist in your final code, but applications may find it useful in certain situations when errors need to be logged before being discarded.Examples
Basic usage:
let a = ; // this iterator sequence is complex. let sum = a.iter .cloned .filter .fold; println!; // let's add some inspect() calls to investigate what's happening let sum = a.iter .cloned .inspect .filter .inspect .fold; println!;This will print:
6 about to filter: 1 about to filter: 4 made it through filter: 4 about to filter: 2 made it through filter: 2 about to filter: 3 6Logging errors before discarding them:
let lines = ; let sum: i32 = lines .iter .map .inspect .filter_map .sum; println!;This will print:
Parsing error: invalid digit found in string Sum: 3fn by_ref(self: &mut Self) -> &mut Self where Self: SizedCreates a "by reference" adapter for this instance of
Iterator.Consuming method calls (direct or indirect calls to
next) on the "by reference" adapter will consume the original iterator, but ownership-taking methods (those with aselfparameter) only take ownership of the "by reference" iterator.This is useful for applying ownership-taking methods (such as
takein the example below) without giving up ownership of the original iterator, so you can use the original iterator afterwards.Uses
impl<I: Iterator + ?Sized> Iterator for &mut I { type Item = I::Item; ...}.Examples
let mut words = .into_iter; // Take the first two words. let hello_world: = words.by_ref.take.collect; assert_eq!; // Collect the rest of the words. // We can only do this because we used `by_ref` earlier. let of_rust: = words.collect; assert_eq!;fn collect<B: FromIterator<<Self as >::Item>>(self: Self) -> B where Self: SizedTransforms an iterator into a collection.
collect()takes ownership of an iterator and produces whichever collection type you request. The iterator itself carries no knowledge of the eventual container; the target collection is chosen entirely by the type you askcollect()to return. This makescollect()one of the more powerful methods in the standard library, and it shows up in a wide variety of contexts.The most basic pattern in which
collect()is used is to turn one collection into another. You take a collection, calliteron it, do a bunch of transformations, and thencollect()at the end.collect()can also create instances of types that are not typical collections. For example, aStringcan be built fromchars, and an iterator of [Result<T, E>]Resultitems can be collected intoResult<Collection<T>, E>. See the examples below for more.Because
collect()is so general, it can cause problems with type inference. As such,collect()is one of the few times you'll see the syntax affectionately known as the 'turbofish':::<>. This helps the inference algorithm understand specifically which collection you're trying to collect into.Examples
Basic usage:
let a = ; let doubled: = a.iter .map .collect; assert_eq!;Note that we needed the
: Vec<i32>on the left-hand side. This is because we could collect into, for example, aVecDeque<T>instead:use VecDeque; let a = ; let doubled: = a.iter.map.collect; assert_eq!; assert_eq!; assert_eq!;Using the 'turbofish' instead of annotating
doubled:let a = ; let doubled = a.iter.map.; assert_eq!;Because
collect()only cares about what you're collecting into, you can still use a partial type hint,_, with the turbofish:let a = ; let doubled = a.iter.map.; assert_eq!;Using
collect()to make aString:let chars = ; let hello: String = chars.into_iter .map .map .collect; assert_eq!;If you have a list of [
Result<T, E>]Results, you can usecollect()to see if any of them failed:let results = ; let result: = results.into_iter.collect; // gives us the first error assert_eq!; let results = ; let result: = results.into_iter.collect; // gives us the list of answers assert_eq!;fn try_collect<B>(self: &mut Self) -> <<<Self as >::Item as >::Residual as Residual<B>>::TryType where Self: Sized, <Self as >::Item: Try<Residual: Residual<B>>, B: FromIterator<<<Self as >::Item as Try>::Output>Fallibly transforms an iterator into a collection, short circuiting if a failure is encountered.
try_collect()is a variation ofcollect()that allows fallible conversions during collection. Its main use case is simplifying conversions from iterators yielding [Option<T>]OptionintoOption<Collection<T>>, or similarly for otherTrytypes (e.g.Result).Importantly,
try_collect()doesn't require that the outerTrytype also implementsFromIterator; only the inner type produced onTry::Outputmust implement it. Concretely, this means that collecting intoControlFlow<_, Vec<i32>>is valid becauseVec<i32>implementsFromIterator, even thoughControlFlowdoesn't.Also, if a failure is encountered during
try_collect(), the iterator is still valid and may continue to be used, in which case it will continue iterating starting after the element that triggered the failure. See the last example below for an example of how this works.Examples
Successfully collecting an iterator of
Option<i32>intoOption<Vec<i32>>:let u = vec!; let v = u.into_iter.; assert_eq!;Failing to collect in the same way:
let u = vec!; let v = u.into_iter.; assert_eq!;A similar example, but with
Result:let u: = vec!; let v = u.into_iter.; assert_eq!; let u = vec!; let v = u.into_iter.; assert_eq!;Finally, even
ControlFlowworks, despite the fact that it doesn't implementFromIterator. Note also that the iterator can continue to be used, even if a failure is encountered:use ; let u = ; let mut it = u.into_iter; let v = it.; assert_eq!; let v = it.; assert_eq!;fn collect_into<E: Extend<<Self as >::Item>>(self: Self, collection: &mut E) -> &mut E where Self: SizedCollects all the items from an iterator into a collection.
This method consumes the iterator and adds all its items to the passed collection. The collection is then returned, so the call chain can be continued.
This is useful when you already have a collection and want to add the iterator items to it.
This method is a convenience method to call Extend::extend, but instead of being called on a collection, it's called on an iterator.
Examples
Basic usage:
let a = ; let mut vec: Vec:: = vec!; a.iter.map.collect_into; a.iter.map.collect_into; assert_eq!;Veccan have a manual set capacity to avoid reallocating it:let a = ; let mut vec: Vec:: = Vecwith_capacity; a.iter.map.collect_into; a.iter.map.collect_into; assert_eq!; assert_eq!;The returned mutable reference can be used to continue the call chain:
let a = ; let mut vec: Vec:: = Vecwith_capacity; let count = a.iter.collect_into.iter.count; assert_eq!; assert_eq!; let count = a.iter.collect_into.iter.count; assert_eq!; assert_eq!;fn partition<B, F>(self: Self, f: F) -> (B, B) where Self: Sized, B: Default + Extend<<Self as >::Item>, F: FnMut(&<Self as >::Item) -> boolConsumes an iterator, creating two collections from it.
The predicate passed to
partition()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 also
is_partitioned()andpartition_in_place().Examples
let a = ; let : = a .into_iter .partition; assert_eq!; assert_eq!;fn partition_in_place<'a, T: 'a, P>(self: Self, predicate: P) -> usize where Self: Sized + DoubleEndedIterator<Item = &'a mut T>, P: FnMut(&T) -> boolReorders the elements of this iterator in-place according to the given predicate, such that all those that return
trueprecede all those that returnfalse. Returns the number oftrueelements 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 evaluates to false and the last element for which it evaluates to true, and repeatedly swaps them.
Time complexity: O(n)
See also
is_partitioned()andpartition().Examples
let mut a = ; // Partition in-place between evens and odds let i = a.iter_mut.partition_in_place; assert_eq!; assert!; // evens assert!; // oddsfn is_partitioned<P>(self: Self, predicate: P) -> bool where Self: Sized, P: FnMut(<Self as >::Item) -> boolChecks if the elements of this iterator are partitioned according to the given predicate, such that all those that return
trueprecede all those that returnfalse.See also
partition()andpartition_in_place().Examples
assert!; assert!;fn try_fold<B, F, R>(self: &mut Self, init: B, f: F) -> R where Self: Sized, F: FnMut(B, <Self as >::Item) -> R, R: Try<Output = B>An iterator method that applies a function as long as it returns successfully, producing a single, final value.
try_fold()takes two arguments: an initial value, and a closure with two arguments: an 'accumulator', and an element. The closure either returns successfully, with the value that the accumulator should have for the next iteration, or it returns failure, with an error value that is propagated back to the caller immediately (short-circuiting).The initial value is the value the accumulator will have on the first call. If applying the closure succeeded against every element of the iterator,
try_fold()returns the final accumulator as success.Folding is useful whenever you have a collection of something, and want to produce a single value from it.
Note to Implementors
Several of the other (forward) methods have default implementations in terms of this one, so try to implement this explicitly if it can do something better than the default
forloop implementation.In particular, try to have this call
try_fold()on the internal parts from which this iterator is composed. If multiple calls are needed, the?operator may be convenient for chaining the accumulator value along, but beware any invariants that need to be upheld before those early returns. This is a&mut selfmethod, so iteration needs to be resumable after hitting an error here.Examples
Basic usage:
let a = ; // the checked sum of all of the elements of the array let sum = a.into_iter.try_fold; assert_eq!;Short-circuiting:
let a = ; let mut iter = a.into_iter; // This sum overflows when adding the 100 element let sum = iter.try_fold; assert_eq!; // Because it short-circuited, the remaining elements are still // available through the iterator. assert_eq!; assert_eq!;While you cannot
breakfrom a closure, theControlFlowtype allows a similar idea:use ControlFlow; let triangular = .try_fold; assert_eq!; let triangular = .try_fold; assert_eq!;fn try_for_each<F, R>(self: &mut Self, f: F) -> R where Self: Sized, F: FnMut(<Self as >::Item) -> R, R: Try<Output = ()>An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error.
This can also be thought of as the fallible form of
for_each()or as the stateless version oftry_fold().Examples
use rename; use ; use Path; let data = ; let res = data.iter.try_for_each; assert!; let mut it = data.iter.cloned; let res = it.try_for_each; assert!; // It short-circuited, so the remaining items are still in the iterator: assert_eq!;The
ControlFlowtype can be used with this method for the situations in which you'd usebreakandcontinuein a normal loop:use ControlFlow; let r = .try_for_each; assert_eq!;fn fold<B, F>(self: Self, init: B, f: F) -> B where Self: Sized, F: FnMut(B, <Self as >::Item) -> BFolds every element into an accumulator by applying an operation, returning the final result.
fold()takes two arguments: an initial value, and a closure with two arguments: an 'accumulator', and an element. The closure returns the value that the accumulator should have for the next iteration.The initial value is the value the accumulator will have on the first call.
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 want to 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 a result is determinable in finite time.Note:
reduce()can be used to use the first element as the initial value, if the accumulator type and item type is the same.Note:
fold()combines elements in a left-associative fashion. For associative operators like+, the order the elements are combined in is not important, but for non-associative operators like-the order will affect the final result. For a right-associative version offold(), see [DoubleEndedIterator::rfold()].Note to Implementors
Several of the other (forward) methods have default implementations in terms of this one, so try to implement this explicitly if it can do something better than the default
forloop implementation.In particular, try to have this call
fold()on the internal parts from which this iterator is composed.Examples
Basic usage:
let a = ; // the sum of all of the elements of the array let sum = a.iter.fold; assert_eq!;Let's walk through each step of the iteration here:
element acc x result 0 1 0 1 1 2 1 2 3 3 3 3 6 And so, our final result,
6.This example demonstrates the left-associative nature of
fold(): it builds a string, starting with an initial value and continuing with each element from the front until the back:let numbers = ; let zero = "0".to_string; let result = numbers.iter.fold; assert_eq!;It's common for people who haven't used iterators a lot to use a
forloop with a list of things to build up a result. Those can be turned intofold()s:let numbers = ; let mut result = 0; // for loop: for i in &numbers // fold: let result2 = numbers.iter.fold; // they're the same assert_eq!;fn reduce<F>(self: Self, f: F) -> Option<<Self as >::Item> where Self: Sized, F: FnMut(<Self as >::Item, <Self as >::Item) -> <Self as >::ItemReduces the elements to a single one, by repeatedly applying a reducing operation.
If the iterator is empty, returns
None; otherwise, returns the result 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 as
fold()with the first element of the iterator as the initial accumulator value, folding every subsequent element into it.Example
let reduced: i32 = .reduce.unwrap_or; assert_eq!; // Which is equivalent to doing it with `fold`: let folded: i32 = .fold; assert_eq!;fn try_reduce<R, impl FnMut(Self::Item, Self::Item) -> R: FnMut(<Self as >::Item, <Self as >::Item) -> R>(self: &mut Self, f: impl FnMut(<Self as >::Item, <Self as >::Item) -> R) -> <<R as >::Residual as Residual<Option<<R as >::Output>>>::TryType where Self: Sized, R: Try<Output = <Self as >::Item, Residual: Residual<Option<<Self as >::Item>>>Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure 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 closure returns
Result<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 either
Some(None)orOk(None)depending on the type of the provided closure.For iterators with at least one element, this is essentially the same as calling
try_fold()with the first element of the iterator as the initial accumulator value.Examples
Safely calculate the sum of a series of numbers:
let numbers: = vec!; let sum = numbers.into_iter.try_reduce; assert_eq!;Determine when a reduction short circuited:
let numbers = vec!; let sum = numbers.into_iter.try_reduce; assert_eq!;Determine when a reduction was not performed because there are no elements:
let numbers: = Vecnew; let sum = numbers.into_iter.try_reduce; assert_eq!;Use a
Resultinstead of an [Option]:let numbers = vec!; let max: = numbers.into_iter.try_reduce; assert_eq!;fn all<F>(self: &mut Self, f: F) -> bool where Self: Sized, F: FnMut(<Self as >::Item) -> boolTests if every element of the iterator matches a predicate.
all()takes a closure that returnstrueorfalse. It applies this closure to each element of the iterator, and if they all returntrue, then so doesall(). If any of them returnfalse, it returnsfalse.all()is short-circuiting; in other words, it will stop processing as soon as it finds afalse, given that no matter what else happens, the result will also befalse.An empty iterator returns
true.Examples
Basic usage:
let a = ; assert!; assert!;Stopping at the first
false:let a = ; let mut iter = a.into_iter; assert!; // we can still use `iter`, as there are more elements. assert_eq!;fn any<F>(self: &mut Self, f: F) -> bool where Self: Sized, F: FnMut(<Self as >::Item) -> boolTests if any element of the iterator matches a predicate.
any()takes a closure that returnstrueorfalse. It applies this closure to each element of the iterator, and if any of them returntrue, then so doesany(). If they all returnfalse, it returnsfalse.any()is short-circuiting; in other words, it will stop processing as soon as it finds atrue, given that no matter what else happens, the result will also betrue.An empty iterator returns
false.Examples
Basic usage:
let a = ; assert!; assert!;Stopping at the first
true:let a = ; let mut iter = a.into_iter; assert!; // we can still use `iter`, as there are more elements. assert_eq!;fn find<P>(self: &mut Self, predicate: P) -> Option<<Self as >::Item> where Self: Sized, P: FnMut(&<Self as >::Item) -> boolSearches for an element of an iterator that satisfies a predicate.
find()takes a closure that returnstrueorfalse. It applies this 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 processing as soon as the closure returnstrue.Because
find()takes a reference, and many iterators iterate over references, this leads to a possibly confusing situation where the argument is a double reference. You can see this effect in the examples below, with&&x.If you need the index of the element, see
position().Examples
Basic usage:
let a = ; assert_eq!; assert_eq!;Iterating over references:
let a = ; // `iter()` yields references i.e. `&i32` and `find()` takes a // reference to each element. assert_eq!; assert_eq!;Stopping at the first
true:let a = ; let mut iter = a.into_iter; assert_eq!; // we can still use `iter`, as there are more elements. assert_eq!;Note that
iter.find(f)is equivalent toiter.filter(f).next().fn find_map<B, F>(self: &mut Self, f: F) -> Option<B> where Self: Sized, F: FnMut(<Self as >::Item) -> Option<B>Applies function to the elements of iterator and returns the first non-none result.
iter.find_map(f)is equivalent toiter.filter_map(f).next().Examples
let a = ; let first_number = a.iter.find_map; assert_eq!;fn try_find<R, impl FnMut(&Self::Item) -> R: FnMut(&<Self as >::Item) -> R>(self: &mut Self, f: impl FnMut(&<Self as >::Item) -> R) -> <<R as >::Residual as Residual<Option<<Self as >::Item>>>::TryType where Self: Sized, R: Try<Output = bool, Residual: Residual<Option<<Self as >::Item>>>Applies function to the elements of iterator and returns the first true result or the first error.
The return type of this method depends on the return type of the closure. If you return
Result<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
let a = ; let is_my_num = ; let result = a.into_iter.try_find; assert_eq!; let result = a.into_iter.try_find; assert!;This also supports other types which implement
Try, not justResult.use NonZero; let a = ; let result = a.into_iter.try_find; assert_eq!; let result = a.into_iter.take.try_find; assert_eq!; let result = a.into_iter.rev.try_find; assert_eq!;fn position<P>(self: &mut Self, predicate: P) -> Option<usize> where Self: Sized, P: FnMut(<Self as >::Item) -> boolSearches for an element in an iterator, returning its index.
position()takes a closure that returnstrueorfalse. It applies this closure to each element of the iterator, and if one of them returnstrue, thenposition()returnsSome(index). If all of them returnfalse, it returnsNone.position()is short-circuiting; in other words, it will stop processing as soon as it finds atrue.Overflow Behavior
The method does no guarding against overflows, so if there are more than
usize::MAXnon-matching elements, it either produces the wrong result or panics. If overflow checks are enabled, a panic is guaranteed.Panics
This function might panic if the iterator has more than
usize::MAXnon-matching elements.Examples
Basic usage:
let a = ; assert_eq!; assert_eq!;Stopping at the first
true:let a = ; let mut iter = a.into_iter; assert_eq!; // we can still use `iter`, as there are more elements. assert_eq!; // The returned index depends on iterator state assert_eq!;fn rposition<P>(self: &mut Self, predicate: P) -> Option<usize> where P: FnMut(<Self as >::Item) -> bool, Self: Sized + ExactSizeIterator + DoubleEndedIteratorSearches for an element in an iterator from the right, returning its index.
rposition()takes a closure that returnstrueorfalse. It applies this 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 stop processing as soon as it finds atrue.Examples
Basic usage:
let a = ; assert_eq!; assert_eq!;Stopping at the first
true:let a = ; let mut iter = a.into_iter; assert_eq!; // we can still use `iter`, as there are more elements. assert_eq!; assert_eq!;fn max(self: Self) -> Option<<Self as >::Item> where Self: Sized, <Self as >::Item: OrdReturns the maximum element of an iterator.
If several elements are equally maximum, the last element is returned. If the iterator is empty,
Noneis returned.Note that
f32/f64doesn't implementOrddue to NaN being incomparable. You can work around this by using [Iterator::reduce]:assert_eq!;Examples
let a = ; let b: = ; assert_eq!; assert_eq!;fn min(self: Self) -> Option<<Self as >::Item> where Self: Sized, <Self as >::Item: OrdReturns the minimum element of an iterator.
If several elements are equally minimum, the first element is returned. If the iterator is empty,
Noneis returned.Note that
f32/f64doesn't implementOrddue to NaN being incomparable. You can work around this by using [Iterator::reduce]:assert_eq!;Examples
let a = ; let b: = ; assert_eq!; assert_eq!;fn max_by_key<B: Ord, F>(self: Self, f: F) -> Option<<Self as >::Item> where Self: Sized, F: FnMut(&<Self as >::Item) -> BReturns the element that gives the maximum value from the specified function.
If several elements are equally maximum, the last element is returned. If the iterator is empty,
Noneis returned.Examples
let a = ; assert_eq!;fn max_by<F>(self: Self, compare: F) -> Option<<Self as >::Item> where Self: Sized, F: FnMut(&<Self as >::Item, &<Self as >::Item) -> OrderingReturns the element that gives the maximum value with respect to the specified comparison function.
If several elements are equally maximum, the last element is returned. If the iterator is empty,
Noneis returned.Examples
let a = ; assert_eq!;fn min_by_key<B: Ord, F>(self: Self, f: F) -> Option<<Self as >::Item> where Self: Sized, F: FnMut(&<Self as >::Item) -> BReturns the element that gives the minimum value from the specified function.
If several elements are equally minimum, the first element is returned. If the iterator is empty,
Noneis returned.Examples
let a = ; assert_eq!;fn min_by<F>(self: Self, compare: F) -> Option<<Self as >::Item> where Self: Sized, F: FnMut(&<Self as >::Item, &<Self as >::Item) -> OrderingReturns the element that gives the minimum value with respect to the specified comparison function.
If several elements are equally minimum, the first element is returned. If the iterator is empty,
Noneis returned.Examples
let a = ; assert_eq!;fn rev(self: Self) -> Rev<Self> where Self: Sized + DoubleEndedIteratorReverses an iterator's direction.
Usually, iterators iterate from left to right. After using
rev(), an iterator will instead iterate from right to left.This is only possible if the iterator has an end, so
rev()only works onDoubleEndedIterators.Examples
let a = ; let mut iter = a.into_iter.rev; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn unzip<A, B, FromA, FromB>(self: 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 two collections: one from the left elements of the pairs, and one from the right elements.This function is, in some sense, the opposite of
zip.Examples
let a = ; let : = a.into_iter.unzip; assert_eq!; assert_eq!; // you can also unzip multiple nested tuples at once let a = ; let : = a.into_iter.unzip; assert_eq!; assert_eq!; assert_eq!;fn copied<'a, T>(self: 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 an iterator overT.Examples
let a = ; let v_copied: = a.iter.copied.collect; // copied is the same as .map(|&x| x) let v_map: = a.iter.map.collect; assert_eq!; assert_eq!;fn cloned<'a, T>(self: Self) -> Cloned<Self> where T: Clone + 'a, Self: Sized + Iterator<Item = &'a T>Creates an iterator which
clones all of its elements.This is useful when you have an iterator over
&T, but you need an iterator overT.There is no guarantee whatsoever about the
clonemethod actually being called or optimized away. So code should not depend on either.Examples
Basic usage:
let a = ; let v_cloned: = a.iter.cloned.collect; // cloned is the same as .map(|&x| x), for integers let v_map: = a.iter.map.collect; assert_eq!; assert_eq!;To get the best performance, try to clone late:
let a = ; // don't do this: let slower: = a.iter.cloned.filter.collect; assert_eq!; // instead call `cloned` late let faster: = a.iter.filter.cloned.collect; assert_eq!;fn cycle(self: Self) -> Cycle<Self> where Self: Sized + CloneRepeats an iterator endlessly.
Instead of stopping at
None, the iterator will instead start again, from the beginning. After iterating again, it will start at the beginning again. And again. And again. Forever. Note that in case the original iterator is empty, the resulting iterator will also be empty.Examples
let a = ; let mut iter = a.into_iter.cycle; loopfn array_chunks<N: usize>(self: Self) -> ArrayChunks<Self, N> where Self: SizedReturns an iterator over
Nelements of the iterator at a time.The chunks do not overlap. If
Ndoes not divide the length of the iterator, then the last up toN-1elements will be omitted and can be retrieved from the [.into_remainder()][ArrayChunks::into_remainder] function of the iterator.Panics
Panics if
Nis zero.Examples
Basic usage:
let mut iter = "lorem".chars.array_chunks; assert_eq!; assert_eq!; assert_eq!; assert_eq!;let data = ; // ^-----^ ^------^ for in data.iter.array_chunksfn sum<S>(self: Self) -> S where Self: Sized, S: Sum<<Self as >::Item>Sums the elements of an iterator.
Takes each element, adds them together, and returns the result.
An empty iterator returns the additive identity ("zero") of the type, which is
0for integers and-0.0for floats.sum()can be used to sum any type implementing [Sum]core::iter::Sum, including [Option]Option::sumand [Result]Result::sum.Panics
When calling
sum()and a primitive integer type is being returned, this method will panic if the computation overflows and overflow checks are enabled.Examples
let a = ; let sum: i32 = a.iter.sum; assert_eq!; let b: = vec!; let sum: f32 = b.iter.sum; assert_eq!;fn product<P>(self: Self) -> P where Self: Sized, P: Product<<Self as >::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 implementing [Product]core::iter::Product, including [Option]Option::productand [Result]Result::product.Panics
When calling
product()and a primitive integer type is being returned, method will panic if the computation overflows and overflow checks are enabled.Examples
assert_eq!; assert_eq!; assert_eq!;fn cmp<I>(self: Self, other: I) -> Ordering where I: IntoIterator<Item = <Self as >::Item>, <Self as >::Item: Ord, Self: SizedLexicographically compares the elements of this
Iteratorwith those of another.Examples
use Ordering; assert_eq!; assert_eq!; assert_eq!;fn cmp_by<I, F>(self: Self, other: I, cmp: F) -> Ordering where Self: Sized, I: IntoIterator, F: FnMut(<Self as >::Item, <I as >::Item) -> OrderingLexicographically compares the elements of this
Iteratorwith those of another with respect to the specified comparison function.Examples
use Ordering; let xs = ; let ys = ; assert_eq!; assert_eq!; assert_eq!;fn partial_cmp<I>(self: Self, other: I) -> Option<Ordering> where I: IntoIterator, <Self as >::Item: PartialOrd<<I as >::Item>, Self: SizedLexicographically compares the
PartialOrdelements of thisIteratorwith those of another. The comparison works like short-circuit evaluation, 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
use Ordering; assert_eq!; assert_eq!; assert_eq!;For floating-point numbers, NaN does not have a total order and will result in
Nonewhen compared:assert_eq!;The results are determined by the order of evaluation.
use Ordering; assert_eq!; assert_eq!; assert_eq!;fn partial_cmp_by<I, F>(self: Self, other: I, partial_cmp: F) -> Option<Ordering> where Self: Sized, I: IntoIterator, F: FnMut(<Self as >::Item, <I as >::Item) -> Option<Ordering>Lexicographically compares the elements of this
Iteratorwith those of another with respect to the specified comparison function.Examples
use Ordering; let xs = ; let ys = ; assert_eq!; assert_eq!; assert_eq!;fn eq<I>(self: Self, other: I) -> bool where I: IntoIterator, <Self as >::Item: PartialEq<<I as >::Item>, Self: SizedDetermines if the elements of this
Iteratorare equal to those of another.Examples
assert_eq!; assert_eq!;fn eq_by<I, F>(self: Self, other: I, eq: F) -> bool where Self: Sized, I: IntoIterator, F: FnMut(<Self as >::Item, <I as >::Item) -> boolDetermines if the elements of this
Iteratorare equal to those of another with respect to the specified equality function.Examples
let xs = ; let ys = ; assert!;fn ne<I>(self: Self, other: I) -> bool where I: IntoIterator, <Self as >::Item: PartialEq<<I as >::Item>, Self: SizedDetermines if the elements of this
Iteratorare not equal to those of another.Examples
assert_eq!; assert_eq!;fn lt<I>(self: Self, other: I) -> bool where I: IntoIterator, <Self as >::Item: PartialOrd<<I as >::Item>, Self: SizedDetermines if the elements of this
Iteratorare lexicographically less than those of another.Examples
assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn le<I>(self: Self, other: I) -> bool where I: IntoIterator, <Self as >::Item: PartialOrd<<I as >::Item>, Self: SizedDetermines if the elements of this
Iteratorare lexicographically less or equal to those of another.Examples
assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn gt<I>(self: Self, other: I) -> bool where I: IntoIterator, <Self as >::Item: PartialOrd<<I as >::Item>, Self: SizedDetermines if the elements of this
Iteratorare lexicographically greater than those of another.Examples
assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn ge<I>(self: Self, other: I) -> bool where I: IntoIterator, <Self as >::Item: PartialOrd<<I as >::Item>, Self: SizedDetermines if the elements of this
Iteratorare lexicographically greater than or equal to those of another.Examples
assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn is_sorted(self: Self) -> bool where Self: Sized, <Self as >::Item: PartialOrdChecks if the elements of this iterator are sorted.
That is, for each element
aand its following elementb,a <= bmust hold. If the iterator yields exactly zero or one element,trueis returned.Note that if
Self::Itemis onlyPartialOrd, but notOrd, the above definition implies that this function returnsfalseif any two consecutive items are not comparable.Examples
assert!; assert!; assert!; assert!; assert!;fn is_sorted_by<F>(self: Self, compare: F) -> bool where Self: Sized, F: FnMut(&<Self as >::Item, &<Self as >::Item) -> boolChecks if the elements of this iterator are sorted using the given comparator function.
Instead of using
PartialOrd::partial_cmp, this function uses the givencomparefunction to determine whether two elements are to be considered in sorted order.Examples
assert!; assert!; assert!; assert!; assert!; assert!;fn is_sorted_by_key<F, K>(self: Self, f: F) -> bool where Self: Sized, F: FnMut(<Self as >::Item) -> K, K: PartialOrdChecks if the elements of this iterator are sorted using the given key extraction function.
Instead of comparing the iterator's elements directly, this function compares the keys of the elements, as determined by
f. Apart from that, it's equivalent tois_sorted; see its documentation for more information.Examples
assert!; assert!;
Implementors
impl<I> Iterator for Cycle<I>impl<I: Iterator + ?Sized> Iterator for &mut Iimpl<'a> Iterator for Chars<'a>impl<T, F> Iterator for Successors<T, F>impl<'a, T, P> Iterator for SplitInclusive<'a, T, P>impl<'a, T> Iterator for ChunksMut<'a, T>impl<I: Iterator<Item = u16>> Iterator for DecodeUtf16<I>impl<'a, P: Pattern> Iterator for MatchIndices<'a, P>impl<'a> Iterator for EscapeUnicode<'a>impl<A: Clone> Iterator for Repeat<A>impl<A: Step> Iterator for RangeIter<A>impl<A, B> Iterator for Zip<A, B>impl<'a, T> Iterator for ChunksExactMut<'a, T>impl<'a> Iterator for Lines<'a>impl<'a, T: 'a, P> Iterator for ChunkBy<'a, T, P>impl<'a, P: Pattern> Iterator for SplitTerminator<'a, P>impl<'a, T> Iterator for Iter<'a, T>impl<'a> Iterator for EscapeDebug<'a>impl<'a, T, P> Iterator for SplitNMut<'a, T, P>impl<'a, T> Iterator for RChunks<'a, T>impl<B, I: Iterator, F> Iterator for FilterMap<I, F>impl<'a> Iterator for SplitAsciiWhitespace<'a>impl<I> Iterator for Rev<I>impl<A: Clone> Iterator for RepeatN<A>impl<T> Iterator for IntoIter<T>impl<I: Iterator, P> Iterator for TakeWhile<I, P>impl<'a, T> Iterator for RChunksExact<'a, T>impl<I, G> Iterator for IntersperseWith<I, G>impl<A: Iterator> Iterator for OptionFlatten<A>impl<'a, T, P> Iterator for RSplitMut<'a, T, P>impl<I> Iterator for Enumerate<I>impl<A: Step> Iterator for RangeFromIter<A>impl<'a, P> Iterator for RMatchIndices<'a, P>impl Iterator for Bytes<'_>impl<'a> Iterator for Utf8Chunks<'a>impl<A: Step> Iterator for RangeFrom<A>impl<'a, A> Iterator for Iter<'a, A>impl<'a, T, P> Iterator for SplitMut<'a, T, P>impl<A: Step> Iterator for Range<A>impl<'a, P> Iterator for RSplitTerminator<'a, P>impl<B, I: Iterator, P> Iterator for MapWhile<I, P>impl Iterator for Bytes<'_>impl<'a, P: Pattern> Iterator for SplitInclusive<'a, P>impl<I> Iterator for Intersperse<I>impl Iterator for EscapeDefaultimpl<'a> Iterator for LinesAny<'a>impl<I> Iterator for Fuse<I>impl Iterator for ToUppercaseimpl<A, B> Iterator for Chain<A, B>impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>impl<'a, T> Iterator for IterMut<'a, T>impl<G: Coroutine<Return = ()> + Unpin> Iterator for FromCoroutine<G>impl<A, F: FnMut() -> A> Iterator for RepeatWith<F>impl<'a, T, P> Iterator for RSplitNMut<'a, T, P>impl<I> Iterator for StepBy<I>impl<'a> Iterator for CharIndices<'a>impl<'a, I, T> Iterator for Copied<I>impl<'a, T: 'a, P> Iterator for ChunkByMut<'a, T, P>impl<I: Iterator, P> Iterator for SkipWhile<I, P>impl<'a, P: Pattern> Iterator for Matches<'a, P>impl<'a, T> Iterator for Chunks<'a, T>impl<I, N: usize> Iterator for ArrayChunks<I, N>impl<'a, T, P> Iterator for SplitN<'a, T, P>impl<'a, T> Iterator for ChunksExact<'a, T>impl<'a, T> Iterator for Iter<'a, T>impl<'a, P: Pattern> Iterator for SplitN<'a, P>impl<'a> Iterator for EscapeDefault<'a>impl<I: Iterator> Iterator for Peekable<I>impl<'a, P: Pattern> Iterator for Split<'a, P>impl<T> Iterator for Empty<T>impl<'a, T, N: usize> Iterator for ArrayWindows<'a, T, N>impl<'a, A> Iterator for IterMut<'a, A>impl<'a, T, P> Iterator for SplitInclusiveMut<'a, T, P>impl<A, F: FnOnce() -> A> Iterator for OnceWith<F>impl<T, N: usize> Iterator for IntoIter<T, N>impl<T> Iterator for Once<T>impl<'a, T> Iterator for RChunksMut<'a, T>impl<'a> Iterator for EncodeUtf16<'a>impl<'a> Iterator for EscapeAscii<'a>impl<'a, P> Iterator for RMatches<'a, P>impl<'a, T, P> Iterator for Split<'a, T, P>impl Iterator for EscapeDebugimpl<'a, T> Iterator for RChunksExactMut<'a, T>impl<'a> Iterator for Source<'a>impl<'a, I, T> Iterator for Cloned<I>impl<I: Iterator> Iterator for ByRefSized<'_, I>impl<T> Iterator for [T]impl<'a> Iterator for SplitWhitespace<'a>impl Iterator for EscapeUnicodeimpl<I, F, R, N: usize> Iterator for MapWindows<I, F, N>impl<'a, P> Iterator for RSplitN<'a, P>impl<'a, P> Iterator for RSplit<'a, P>impl Iterator for EscapeDefaultimpl<I, U> Iterator for Flatten<I>impl<'a, T, P> Iterator for RSplitN<'a, T, P>impl Iterator for ToLowercaseimpl<T, F> Iterator for FromFn<F>impl<'a, T> Iterator for IterMut<'a, T>impl<B, I, St, F> Iterator for Scan<I, St, F>impl<A: Step> Iterator for RangeInclusiveIter<A>impl<I: Iterator, F> Iterator for Inspect<I, F>impl<A: Step> Iterator for RangeInclusive<A>impl<I> Iterator for Skip<I>impl<A> Iterator for IntoIter<A>impl<'a, T, P> Iterator for RSplit<'a, T, P>impl<B, I: Iterator, F> Iterator for Map<I, F>impl<I> Iterator for Take<I>impl<I: Iterator, P> Iterator for Filter<I, P>impl<'a, T> Iterator for Windows<'a, T>