Trait std::iter::Iterator
[−]
[src]
pub trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; fn size_hint(&self) -> (usize, Option<usize>) { ... } fn count(self) -> usize { ... } fn last(self) -> Option<Self::Item> { ... } fn nth(&mut self, n: usize) -> Option<Self::Item> { ... } fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where U: IntoIterator<Item=Self::Item> { ... } fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where U: IntoIterator { ... } fn map<B, F>(self, f: F) -> Map<Self, F> where F: FnMut(Self::Item) -> B { ... } fn filter<P>(self, predicate: P) -> Filter<Self, P> where P: FnMut(&Self::Item) -> bool { ... } fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where F: FnMut(Self::Item) -> Option<B> { ... } fn enumerate(self) -> Enumerate<Self> { ... } fn peekable(self) -> Peekable<Self> { ... } fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where P: FnMut(&Self::Item) -> bool { ... } fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where P: FnMut(&Self::Item) -> bool { ... } fn skip(self, n: usize) -> Skip<Self> { ... } fn take(self, n: usize) -> Take<Self> { ... } fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F> where F: FnMut(&mut St, Self::Item) -> Option<B> { ... } fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> where U: IntoIterator, F: FnMut(Self::Item) -> U { ... } fn fuse(self) -> Fuse<Self> { ... } fn inspect<F>(self, f: F) -> Inspect<Self, F> where F: FnMut(&Self::Item) -> () { ... } fn by_ref(&mut self) -> &mut Self { ... } fn collect<B>(self) -> B where B: FromIterator<Self::Item> { ... } fn partition<B, F>(self, f: F) -> (B, B) where F: FnMut(&Self::Item) -> bool, B: Default + Extend<Self::Item> { ... } fn fold<B, F>(self, init: B, f: F) -> B where F: FnMut(B, Self::Item) -> B { ... } fn all<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool { ... } fn any<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool { ... } fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where P: FnMut(&Self::Item) -> bool { ... } fn position<P>(&mut self, predicate: P) -> Option<usize> where P: FnMut(Self::Item) -> bool { ... } fn rposition<P>(&mut self, predicate: P) -> Option<usize> where Self: ExactSizeIterator + DoubleEndedIterator, P: FnMut(Self::Item) -> bool { ... } fn max(self) -> Option<Self::Item> where Self::Item: Ord { ... } fn min(self) -> Option<Self::Item> where Self::Item: Ord { ... } fn min_max(self) -> MinMaxResult<Self::Item> where Self::Item: Ord { ... } fn max_by<B, F>(self, f: F) -> Option<Self::Item> where B: Ord, F: FnMut(&Self::Item) -> B { ... } fn min_by<B, F>(self, f: F) -> Option<Self::Item> where B: Ord, F: FnMut(&Self::Item) -> B { ... } fn rev(self) -> Rev<Self> where Self: DoubleEndedIterator { ... } fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where FromA: Default + Extend<A>, FromB: Default + Extend<B>, Self: Iterator<Item=(A, B)> { ... } fn cloned<'a, T>(self) -> Cloned<Self> where T: 'a + Clone, Self: Iterator<Item=&'a T> { ... } fn cycle(self) -> Cycle<Self> where Self: Clone { ... } fn reverse_in_place<'a, T>(&mut self) where Self: Iterator<Item=&'a mut T> + DoubleEndedIterator, T: 'a { ... } fn sum<S = Self::Item>(self) -> S where S: Add<Self::Item, Output=S> + Zero { ... } fn product<P = Self::Item>(self) -> P where P: Mul<Self::Item, Output=P> + One { ... } }
An interface for dealing with "external iterators". These types of iterators can be resumed at any time as all state is stored internally as opposed to being located on the call stack.
The Iterator protocol states that an iterator yields a (potentially-empty,
potentially-infinite) sequence of values, and returns None
to signal that
it's finished. The Iterator protocol does not define behavior after None
is returned. A concrete Iterator implementation may choose to behave however
it wishes, either by returning None
infinitely, or by doing something
else.
Associated Types
type Item
The type of the elements being iterated
Required Methods
fn next(&mut self) -> Option<Self::Item>
Advances the iterator and returns the next value. Returns None
when the
end is reached.
Provided Methods
fn size_hint(&self) -> (usize, Option<usize>)
Returns a lower and upper bound on the remaining length of the iterator.
An upper bound of None
means either there is no known upper bound, or
the upper bound does not fit within a usize
.
fn count(self) -> usize
Counts the number of elements in this iterator.
Overflow Behavior
The method does no guarding against overflows, so counting elements of
an iterator with more than usize::MAX
elements either produces the
wrong result or panics. If debug assertions are enabled, a panic is
guaranteed.
Panics
This functions might panic if the iterator has more than usize::MAX
elements.
Examples
fn main() { let a = [1, 2, 3, 4, 5]; assert_eq!(a.iter().count(), 5); }let a = [1, 2, 3, 4, 5]; assert_eq!(a.iter().count(), 5);
fn last(self) -> Option<Self::Item>
Loops through the entire iterator, returning the last element.
Examples
fn main() { let a = [1, 2, 3, 4, 5]; assert_eq!(a.iter().last(), Some(&5)); }let a = [1, 2, 3, 4, 5]; assert_eq!(a.iter().last(), Some(&5));
fn nth(&mut self, n: usize) -> Option<Self::Item>
Loops through n
iterations, returning the n
th element of the
iterator.
Examples
fn main() { let a = [1, 2, 3, 4, 5]; let mut it = a.iter(); assert_eq!(it.nth(2), Some(&3)); assert_eq!(it.nth(2), None); }let a = [1, 2, 3, 4, 5]; let mut it = a.iter(); assert_eq!(it.nth(2), Some(&3)); assert_eq!(it.nth(2), None);
fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where U: IntoIterator<Item=Self::Item>
Chain this iterator with another, returning a new iterator that will finish iterating over the current iterator, and then iterate over the other specified iterator.
Examples
fn main() { let a = [0]; let b = [1]; let mut it = a.iter().chain(b.iter()); assert_eq!(it.next(), Some(&0)); assert_eq!(it.next(), Some(&1)); assert!(it.next().is_none()); }let a = [0]; let b = [1]; let mut it = a.iter().chain(b.iter()); assert_eq!(it.next(), Some(&0)); assert_eq!(it.next(), Some(&1)); assert!(it.next().is_none());
fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where U: IntoIterator
Creates an iterator that iterates over both this and the specified
iterators simultaneously, yielding the two elements as pairs. When
either iterator returns None
, all further invocations of next()
will return None
.
Examples
fn main() { let a = [0]; let b = [1]; let mut it = a.iter().zip(b.iter()); assert_eq!(it.next(), Some((&0, &1))); assert!(it.next().is_none()); }let a = [0]; let b = [1]; let mut it = a.iter().zip(b.iter()); assert_eq!(it.next(), Some((&0, &1))); assert!(it.next().is_none());
zip
can provide similar functionality to enumerate
:
for pair in "foo".chars().enumerate() { println!("{:?}", pair); } for pair in (0..).zip("foo".chars()) { println!("{:?}", pair); }
both produce the same output.
fn map<B, F>(self, f: F) -> Map<Self, F> where F: FnMut(Self::Item) -> B
Creates a new iterator that will apply the specified function to each element returned by the first, yielding the mapped element instead.
Examples
fn main() { let a = [1, 2]; let mut it = a.iter().map(|&x| 2 * x); assert_eq!(it.next(), Some(2)); assert_eq!(it.next(), Some(4)); assert!(it.next().is_none()); }let a = [1, 2]; let mut it = a.iter().map(|&x| 2 * x); assert_eq!(it.next(), Some(2)); assert_eq!(it.next(), Some(4)); assert!(it.next().is_none());
fn filter<P>(self, predicate: P) -> Filter<Self, P> where P: FnMut(&Self::Item) -> bool
Creates an iterator that applies the predicate to each element returned
by this iterator. The only elements that will be yielded are those that
make the predicate evaluate to true
.
Examples
fn main() { let a = [1, 2]; let mut it = a.iter().filter(|&x| *x > 1); assert_eq!(it.next(), Some(&2)); assert!(it.next().is_none()); }let a = [1, 2]; let mut it = a.iter().filter(|&x| *x > 1); assert_eq!(it.next(), Some(&2)); assert!(it.next().is_none());
fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where F: FnMut(Self::Item) -> Option<B>
Creates an iterator that both filters and maps elements.
If the specified function returns None
, the element is skipped.
Otherwise the option is unwrapped and the new value is yielded.
Examples
fn main() { let a = [1, 2]; let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None}); assert_eq!(it.next(), Some(4)); assert!(it.next().is_none()); }let a = [1, 2]; let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None}); assert_eq!(it.next(), Some(4)); assert!(it.next().is_none());
fn enumerate(self) -> Enumerate<Self>
Creates an iterator that yields pairs (i, val)
where i
is the
current index of iteration and val
is the value returned by the
iterator.
enumerate
keeps its count as a usize
. If you want to count by a
different sized integer, the zip
function provides similar
functionality.
Overflow Behavior
The method does no guarding against overflows, so enumerating more than
usize::MAX
elements either produces the wrong result or panics. If
debug assertions are enabled, a panic is guaranteed.
Panics
The returned iterator might panic if the to-be-returned index would
overflow a usize
.
Examples
fn main() { let a = [100, 200]; let mut it = a.iter().enumerate(); assert_eq!(it.next(), Some((0, &100))); assert_eq!(it.next(), Some((1, &200))); assert!(it.next().is_none()); }let a = [100, 200]; let mut it = a.iter().enumerate(); assert_eq!(it.next(), Some((0, &100))); assert_eq!(it.next(), Some((1, &200))); assert!(it.next().is_none());
fn peekable(self) -> Peekable<Self>
Creates an iterator that has a .peek()
method
that returns an optional reference to the next element.
Examples
#![feature(core)] fn main() { let xs = [100, 200, 300]; let mut it = xs.iter().cloned().peekable(); assert_eq!(*it.peek().unwrap(), 100); assert_eq!(it.next().unwrap(), 100); assert_eq!(it.next().unwrap(), 200); assert_eq!(*it.peek().unwrap(), 300); assert_eq!(*it.peek().unwrap(), 300); assert_eq!(it.next().unwrap(), 300); assert!(it.peek().is_none()); assert!(it.next().is_none()); }let xs = [100, 200, 300]; let mut it = xs.iter().cloned().peekable(); assert_eq!(*it.peek().unwrap(), 100); assert_eq!(it.next().unwrap(), 100); assert_eq!(it.next().unwrap(), 200); assert_eq!(*it.peek().unwrap(), 300); assert_eq!(*it.peek().unwrap(), 300); assert_eq!(it.next().unwrap(), 300); assert!(it.peek().is_none()); assert!(it.next().is_none());
fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where P: FnMut(&Self::Item) -> bool
Creates an iterator that invokes the predicate on elements until it returns false. Once the predicate returns false, that element and all further elements are yielded.
Examples
fn main() { let a = [1, 2, 3, 4, 5]; let mut it = a.iter().skip_while(|&a| *a < 3); assert_eq!(it.next(), Some(&3)); assert_eq!(it.next(), Some(&4)); assert_eq!(it.next(), Some(&5)); assert!(it.next().is_none()); }let a = [1, 2, 3, 4, 5]; let mut it = a.iter().skip_while(|&a| *a < 3); assert_eq!(it.next(), Some(&3)); assert_eq!(it.next(), Some(&4)); assert_eq!(it.next(), Some(&5)); assert!(it.next().is_none());
fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where P: FnMut(&Self::Item) -> bool
Creates an iterator that yields elements so long as the predicate returns true. After the predicate returns false for the first time, no further elements will be yielded.
Examples
fn main() { let a = [1, 2, 3, 4, 5]; let mut it = a.iter().take_while(|&a| *a < 3); assert_eq!(it.next(), Some(&1)); assert_eq!(it.next(), Some(&2)); assert!(it.next().is_none()); }let a = [1, 2, 3, 4, 5]; let mut it = a.iter().take_while(|&a| *a < 3); assert_eq!(it.next(), Some(&1)); assert_eq!(it.next(), Some(&2)); assert!(it.next().is_none());
fn skip(self, n: usize) -> Skip<Self>
Creates an iterator that skips the first n
elements of this iterator,
and then yields all further items.
Examples
fn main() { let a = [1, 2, 3, 4, 5]; let mut it = a.iter().skip(3); assert_eq!(it.next(), Some(&4)); assert_eq!(it.next(), Some(&5)); assert!(it.next().is_none()); }let a = [1, 2, 3, 4, 5]; let mut it = a.iter().skip(3); assert_eq!(it.next(), Some(&4)); assert_eq!(it.next(), Some(&5)); assert!(it.next().is_none());
fn take(self, n: usize) -> Take<Self>
Creates an iterator that yields the first n
elements of this
iterator.
Examples
fn main() { let a = [1, 2, 3, 4, 5]; let mut it = a.iter().take(3); assert_eq!(it.next(), Some(&1)); assert_eq!(it.next(), Some(&2)); assert_eq!(it.next(), Some(&3)); assert!(it.next().is_none()); }let a = [1, 2, 3, 4, 5]; let mut it = a.iter().take(3); assert_eq!(it.next(), Some(&1)); assert_eq!(it.next(), Some(&2)); assert_eq!(it.next(), Some(&3)); assert!(it.next().is_none());
fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F> where F: FnMut(&mut St, Self::Item) -> Option<B>
Creates a new iterator that behaves in a similar fashion to fold.
There is a state which is passed between each iteration and can be
mutated as necessary. The yielded values from the closure are yielded
from the Scan instance when not None
.
Examples
fn main() { let a = [1, 2, 3, 4, 5]; let mut it = a.iter().scan(1, |fac, &x| { *fac = *fac * x; Some(*fac) }); assert_eq!(it.next(), Some(1)); assert_eq!(it.next(), Some(2)); assert_eq!(it.next(), Some(6)); assert_eq!(it.next(), Some(24)); assert_eq!(it.next(), Some(120)); assert!(it.next().is_none()); }let a = [1, 2, 3, 4, 5]; let mut it = a.iter().scan(1, |fac, &x| { *fac = *fac * x; Some(*fac) }); assert_eq!(it.next(), Some(1)); assert_eq!(it.next(), Some(2)); assert_eq!(it.next(), Some(6)); assert_eq!(it.next(), Some(24)); assert_eq!(it.next(), Some(120)); assert!(it.next().is_none());
fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> where U: IntoIterator, F: FnMut(Self::Item) -> U
Takes a function that maps each element to a new iterator and yields all the elements of the produced iterators.
This is useful for unraveling nested structures.
Examples
fn main() { let words = ["alpha", "beta", "gamma"]; let merged: String = words.iter() .flat_map(|s| s.chars()) .collect(); assert_eq!(merged, "alphabetagamma"); }let words = ["alpha", "beta", "gamma"]; let merged: String = words.iter() .flat_map(|s| s.chars()) .collect(); assert_eq!(merged, "alphabetagamma");
fn fuse(self) -> Fuse<Self>
Creates an iterator that yields None
forever after the underlying
iterator yields None
. Random-access iterator behavior is not
affected, only single and double-ended iterator behavior.
Examples
fn main() { fn process<U: Iterator<Item=i32>>(it: U) -> i32 { let mut it = it.fuse(); let mut sum = 0; for x in it.by_ref() { if x > 5 { break; } sum += x; } // did we exhaust the iterator? if it.next().is_none() { sum += 1000; } sum } let x = vec![1, 2, 3, 7, 8, 9]; assert_eq!(process(x.into_iter()), 6); let x = vec![1, 2, 3]; assert_eq!(process(x.into_iter()), 1006); }fn process<U: Iterator<Item=i32>>(it: U) -> i32 { let mut it = it.fuse(); let mut sum = 0; for x in it.by_ref() { if x > 5 { break; } sum += x; } // did we exhaust the iterator? if it.next().is_none() { sum += 1000; } sum } let x = vec![1, 2, 3, 7, 8, 9]; assert_eq!(process(x.into_iter()), 6); let x = vec![1, 2, 3]; assert_eq!(process(x.into_iter()), 1006);
fn inspect<F>(self, f: F) -> Inspect<Self, F> where F: FnMut(&Self::Item) -> ()
Creates an iterator that calls a function with a reference to each element before yielding it. This is often useful for debugging an iterator pipeline.
Examples
#![feature(core)] fn main() { let a = [1, 4, 2, 3, 8, 9, 6]; let sum: i32 = a.iter() .map(|x| *x) .inspect(|&x| println!("filtering {}", x)) .filter(|&x| x % 2 == 0) .inspect(|&x| println!("{} made it through", x)) .sum(); println!("{}", sum); }let a = [1, 4, 2, 3, 8, 9, 6]; let sum: i32 = a.iter() .map(|x| *x) .inspect(|&x| println!("filtering {}", x)) .filter(|&x| x % 2 == 0) .inspect(|&x| println!("{} made it through", x)) .sum(); println!("{}", sum);
fn by_ref(&mut self) -> &mut Self
Creates a wrapper around a mutable reference to the iterator.
This is useful to allow applying iterator adaptors while still retaining ownership of the original iterator value.
Examples
fn main() { let mut it = 0..10; // sum the first five values let partial_sum = it.by_ref().take(5).fold(0, |a, b| a + b); assert_eq!(partial_sum, 10); assert_eq!(it.next(), Some(5)); }let mut it = 0..10; // sum the first five values let partial_sum = it.by_ref().take(5).fold(0, |a, b| a + b); assert_eq!(partial_sum, 10); assert_eq!(it.next(), Some(5));
fn collect<B>(self) -> B where B: FromIterator<Self::Item>
Loops through the entire iterator, collecting all of the elements into
a container implementing FromIterator
.
Examples
fn main() { let expected = [1, 2, 3, 4, 5]; let actual: Vec<_> = expected.iter().cloned().collect(); assert_eq!(actual, expected); }let expected = [1, 2, 3, 4, 5]; let actual: Vec<_> = expected.iter().cloned().collect(); assert_eq!(actual, expected);
fn partition<B, F>(self, f: F) -> (B, B) where F: FnMut(&Self::Item) -> bool, B: Default + Extend<Self::Item>
Loops through the entire iterator, collecting all of the elements into one of two containers, depending on a predicate. The elements of the first container satisfy the predicate, while the elements of the second do not.
#![feature(core)] fn main() { let vec = vec![1, 2, 3, 4]; let (even, odd): (Vec<_>, Vec<_>) = vec.into_iter().partition(|&n| n % 2 == 0); assert_eq!(even, [2, 4]); assert_eq!(odd, [1, 3]); }let vec = vec![1, 2, 3, 4]; let (even, odd): (Vec<_>, Vec<_>) = vec.into_iter().partition(|&n| n % 2 == 0); assert_eq!(even, [2, 4]); assert_eq!(odd, [1, 3]);
fn fold<B, F>(self, init: B, f: F) -> B where F: FnMut(B, Self::Item) -> B
Performs a fold operation over the entire iterator, returning the eventual state at the end of the iteration.
This operation is sometimes called 'reduce' or 'inject'.
Examples
fn main() { let a = [1, 2, 3, 4, 5]; assert_eq!(a.iter().fold(0, |acc, &item| acc + item), 15); }let a = [1, 2, 3, 4, 5]; assert_eq!(a.iter().fold(0, |acc, &item| acc + item), 15);
fn all<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool
Tests whether the predicate holds true for all elements in the iterator.
Examples
fn main() { let a = [1, 2, 3, 4, 5]; assert!(a.iter().all(|x| *x > 0)); assert!(!a.iter().all(|x| *x > 2)); }let a = [1, 2, 3, 4, 5]; assert!(a.iter().all(|x| *x > 0)); assert!(!a.iter().all(|x| *x > 2));
fn any<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool
Tests whether any element of an iterator satisfies the specified predicate.
Does not consume the iterator past the first found element.
Examples
fn main() { let a = [1, 2, 3, 4, 5]; let mut it = a.iter(); assert!(it.any(|x| *x == 3)); assert_eq!(it.collect::<Vec<_>>(), [&4, &5]); }let a = [1, 2, 3, 4, 5]; let mut it = a.iter(); assert!(it.any(|x| *x == 3)); assert_eq!(it.collect::<Vec<_>>(), [&4, &5]);
fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where P: FnMut(&Self::Item) -> bool
Returns the first element satisfying the specified predicate.
Does not consume the iterator past the first found element.
Examples
fn main() { let a = [1, 2, 3, 4, 5]; let mut it = a.iter(); assert_eq!(it.find(|&x| *x == 3), Some(&3)); assert_eq!(it.collect::<Vec<_>>(), [&4, &5]); }let a = [1, 2, 3, 4, 5]; let mut it = a.iter(); assert_eq!(it.find(|&x| *x == 3), Some(&3)); assert_eq!(it.collect::<Vec<_>>(), [&4, &5]);
fn position<P>(&mut self, predicate: P) -> Option<usize> where P: FnMut(Self::Item) -> bool
Returns the index of the first element satisfying the specified predicate
Does not consume the iterator past the first found element.
Overflow Behavior
The method does no guarding against overflows, so if there are more
than usize::MAX
non-matching elements, it either produces the wrong
result or panics. If debug assertions are enabled, a panic is
guaranteed.
Panics
This functions might panic if the iterator has more than usize::MAX
non-matching elements.
Examples
fn main() { let a = [1, 2, 3, 4, 5]; let mut it = a.iter(); assert_eq!(it.position(|x| *x == 3), Some(2)); assert_eq!(it.collect::<Vec<_>>(), [&4, &5]); }let a = [1, 2, 3, 4, 5]; let mut it = a.iter(); assert_eq!(it.position(|x| *x == 3), Some(2)); assert_eq!(it.collect::<Vec<_>>(), [&4, &5]);
fn rposition<P>(&mut self, predicate: P) -> Option<usize> where Self: ExactSizeIterator + DoubleEndedIterator, P: FnMut(Self::Item) -> bool
Returns the index of the last element satisfying the specified predicate
If no element matches, None
is returned.
Does not consume the iterator before the first found element.
Examples
fn main() { let a = [1, 2, 2, 4, 5]; let mut it = a.iter(); assert_eq!(it.rposition(|x| *x == 2), Some(2)); assert_eq!(it.collect::<Vec<_>>(), [&1, &2]); }let a = [1, 2, 2, 4, 5]; let mut it = a.iter(); assert_eq!(it.rposition(|x| *x == 2), Some(2)); assert_eq!(it.collect::<Vec<_>>(), [&1, &2]);
fn max(self) -> Option<Self::Item> where Self::Item: Ord
Consumes the entire iterator to return the maximum element.
Returns the rightmost element if the comparison determines two elements to be equally maximum.
Examples
fn main() { let a = [1, 2, 3, 4, 5]; assert_eq!(a.iter().max(), Some(&5)); }let a = [1, 2, 3, 4, 5]; assert_eq!(a.iter().max(), Some(&5));
fn min(self) -> Option<Self::Item> where Self::Item: Ord
Consumes the entire iterator to return the minimum element.
Returns the leftmost element if the comparison determines two elements to be equally minimum.
Examples
fn main() { let a = [1, 2, 3, 4, 5]; assert_eq!(a.iter().min(), Some(&1)); }let a = [1, 2, 3, 4, 5]; assert_eq!(a.iter().min(), Some(&1));
fn min_max(self) -> MinMaxResult<Self::Item> where Self::Item: Ord
: return type may change
min_max
finds the minimum and maximum elements in the iterator.
The return type MinMaxResult
is an enum of three variants:
NoElements
if the iterator is empty.OneElement(x)
if the iterator has exactly one element.MinMax(x, y)
is returned otherwise, wherex <= y
. Two values are equal if and only if there is more than one element in the iterator and all elements are equal.
On an iterator of length n
, min_max
does 1.5 * n
comparisons,
and so is faster than calling min
and max
separately which does 2 * n
comparisons.
Examples
#![feature(core)] fn main() { use std::iter::MinMaxResult::{NoElements, OneElement, MinMax}; let a: [i32; 0] = []; assert_eq!(a.iter().min_max(), NoElements); let a = [1]; assert_eq!(a.iter().min_max(), OneElement(&1)); let a = [1, 2, 3, 4, 5]; assert_eq!(a.iter().min_max(), MinMax(&1, &5)); let a = [1, 1, 1, 1]; assert_eq!(a.iter().min_max(), MinMax(&1, &1)); }use std::iter::MinMaxResult::{NoElements, OneElement, MinMax}; let a: [i32; 0] = []; assert_eq!(a.iter().min_max(), NoElements); let a = [1]; assert_eq!(a.iter().min_max(), OneElement(&1)); let a = [1, 2, 3, 4, 5]; assert_eq!(a.iter().min_max(), MinMax(&1, &5)); let a = [1, 1, 1, 1]; assert_eq!(a.iter().min_max(), MinMax(&1, &1));
fn max_by<B, F>(self, f: F) -> Option<Self::Item> where B: Ord, F: FnMut(&Self::Item) -> B
: may want to produce an Ordering directly; see #15311
Returns the element that gives the maximum value from the specified function.
Returns the rightmost element if the comparison determines two elements to be equally maximum.
Examples
#![feature(core)] fn main() { let a = [-3_i32, 0, 1, 5, -10]; assert_eq!(*a.iter().max_by(|x| x.abs()).unwrap(), -10); }let a = [-3_i32, 0, 1, 5, -10]; assert_eq!(*a.iter().max_by(|x| x.abs()).unwrap(), -10);
fn min_by<B, F>(self, f: F) -> Option<Self::Item> where B: Ord, F: FnMut(&Self::Item) -> B
: may want to produce an Ordering directly; see #15311
Returns the element that gives the minimum value from the specified function.
Returns the leftmost element if the comparison determines two elements to be equally minimum.
Examples
#![feature(core)] fn main() { let a = [-3_i32, 0, 1, 5, -10]; assert_eq!(*a.iter().min_by(|x| x.abs()).unwrap(), 0); }let a = [-3_i32, 0, 1, 5, -10]; assert_eq!(*a.iter().min_by(|x| x.abs()).unwrap(), 0);
fn rev(self) -> Rev<Self> where Self: DoubleEndedIterator
Change the direction of the iterator
The flipped iterator swaps the ends on an iterator that can already be iterated from the front and from the back.
If the iterator also implements RandomAccessIterator, the flipped iterator is also random access, with the indices starting at the back of the original iterator.
Note: Random access with flipped indices still only applies to the first
std::usize::MAX
elements of the original iterator.
fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where FromA: Default + Extend<A>, FromB: Default + Extend<B>, Self: Iterator<Item=(A, B)>
Converts an iterator of pairs into a pair of containers.
Loops through the entire iterator, collecting the first component of each item into one new container, and the second component into another.
Examples
#![feature(core)] fn main() { let a = [(1, 2), (3, 4)]; let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip(); assert_eq!(left, [1, 3]); assert_eq!(right, [2, 4]); }let a = [(1, 2), (3, 4)]; let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip(); assert_eq!(left, [1, 3]); assert_eq!(right, [2, 4]);
fn cloned<'a, T>(self) -> Cloned<Self> where T: 'a + Clone, Self: Iterator<Item=&'a T>
Creates an iterator that clones the elements it yields.
This is useful for converting an Iterator<&T> to an Iteratormap(|&x| x)
.
Examples
fn main() { let a = [0, 1, 2]; let v_cloned: Vec<_> = a.iter().cloned().collect(); let v_map: Vec<_> = a.iter().map(|&x| x).collect(); assert_eq!(v_cloned, v_map); }let a = [0, 1, 2]; let v_cloned: Vec<_> = a.iter().cloned().collect(); let v_map: Vec<_> = a.iter().map(|&x| x).collect(); assert_eq!(v_cloned, v_map);
fn cycle(self) -> Cycle<Self> where Self: Clone
Repeats an iterator endlessly
Examples
fn main() { let a = [1, 2]; let mut it = a.iter().cycle(); assert_eq!(it.next(), Some(&1)); assert_eq!(it.next(), Some(&2)); assert_eq!(it.next(), Some(&1)); }let a = [1, 2]; let mut it = a.iter().cycle(); assert_eq!(it.next(), Some(&1)); assert_eq!(it.next(), Some(&2)); assert_eq!(it.next(), Some(&1));
fn reverse_in_place<'a, T>(&mut self) where Self: Iterator<Item=&'a mut T> + DoubleEndedIterator, T: 'a
: uncertain about placement or widespread use
Use an iterator to reverse a container in place.
fn sum<S = Self::Item>(self) -> S where S: Add<Self::Item, Output=S> + Zero
Iterates over the entire iterator, summing up all the elements
Examples
#![feature(core)] fn main() { let a = [1, 2, 3, 4, 5]; let it = a.iter(); assert_eq!(it.sum::<i32>(), 15); }let a = [1, 2, 3, 4, 5]; let it = a.iter(); assert_eq!(it.sum::<i32>(), 15);
fn product<P = Self::Item>(self) -> P where P: Mul<Self::Item, Output=P> + One
Iterates over the entire iterator, multiplying all the elements
Examples
#![feature(core)] fn main() { fn factorial(n: u32) -> u32 { (1..).take_while(|&i| i <= n).product() } assert_eq!(factorial(0), 1); assert_eq!(factorial(1), 1); assert_eq!(factorial(5), 120); }fn factorial(n: u32) -> u32 { (1..).take_while(|&i| i <= n).product() } assert_eq!(factorial(0), 1); assert_eq!(factorial(1), 1); assert_eq!(factorial(5), 120);
Implementors
impl Iterator for EscapeUnicode
impl Iterator for EscapeDefault
impl<'a, I> Iterator for &'a mut I where I: Iterator + ?Sized
impl<I> Iterator for Rev<I> where I: DoubleEndedIterator
impl<'a, I, T> Iterator for Cloned<I> where T: 'a + Clone, I: Iterator<Item=&'a T>
impl<I> Iterator for Cycle<I> where I: Clone + Iterator
impl<A, B> Iterator for Chain<A, B> where A: Iterator, B: Iterator<Item=A::Item>
impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
impl<B, I, F> Iterator for Map<I, F> where I: Iterator, F: FnMut(I::Item) -> B
impl<I, P> Iterator for Filter<I, P> where I: Iterator, P: FnMut(&I::Item) -> bool
impl<B, I, F> Iterator for FilterMap<I, F> where I: Iterator, F: FnMut(I::Item) -> Option<B>
impl<I> Iterator for Enumerate<I> where I: Iterator
impl<I> Iterator for Peekable<I> where I: Iterator
impl<I, P> Iterator for SkipWhile<I, P> where I: Iterator, P: FnMut(&I::Item) -> bool
impl<I, P> Iterator for TakeWhile<I, P> where I: Iterator, P: FnMut(&I::Item) -> bool
impl<I> Iterator for Skip<I> where I: Iterator
impl<I> Iterator for Take<I> where I: Iterator
impl<B, I, St, F> Iterator for Scan<I, St, F> where I: Iterator, F: FnMut(&mut St, I::Item) -> Option<B>
impl<I, U, F> Iterator for FlatMap<I, U, F> where I: Iterator, U: IntoIterator, F: FnMut(I::Item) -> U
impl<I> Iterator for Fuse<I> where I: Iterator
impl<I, F> Iterator for Inspect<I, F> where I: Iterator, F: FnMut(&I::Item) -> ()
impl<A, St, F> Iterator for Unfold<St, F> where F: FnMut(&mut St) -> Option<A>
impl<A> Iterator for StepBy<A, RangeFrom<A>> where A: Clone, &'a A: Add<&'a A>, &'a A::Output == A
impl<A> Iterator for RangeInclusive<A> where A: PartialEq<A> + Step + One + Clone, &'a A: Add<&'a A>, &'a A::Output == A
impl<A> Iterator for StepBy<A, Range<A>> where A: Zero + Clone + Step
impl<A> Iterator for Range<A> where A: One + Step, &'a A: Add<&'a A>, &'a A::Output == A
impl<A> Iterator for RangeFrom<A> where A: One + Step, &'a A: Add<&'a A>, &'a A::Output == A
impl<A> Iterator for Repeat<A> where A: Clone
impl<A> Iterator for Item<A>
impl<'a, A> Iterator for Iter<'a, A>
impl<'a, A> Iterator for IterMut<'a, A>
impl<A> Iterator for IntoIter<A>
impl<'a, T> Iterator for Iter<'a, T>
impl<'a, T> Iterator for IterMut<'a, T>
impl<T> Iterator for IntoIter<T>
impl<'a, T> Iterator for Iter<'a, T>
impl<'a, T> Iterator for IterMut<'a, T>
impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool
impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool
impl<T, I> Iterator for GenericSplitN<I> where I: SplitIter<Item=T>
impl<'a, T, P> Iterator for SplitN<'a, T, P> where P: FnMut(&T) -> bool
impl<'a, T, P> Iterator for RSplitN<'a, T, P> where P: FnMut(&T) -> bool
impl<'a, T, P> Iterator for SplitNMut<'a, T, P> where P: FnMut(&T) -> bool
impl<'a, T, P> Iterator for RSplitNMut<'a, T, P> where P: FnMut(&T) -> bool
impl<'a, T> Iterator for Windows<'a, T>
impl<'a, T> Iterator for Chunks<'a, T>
impl<'a, T> Iterator for ChunksMut<'a, T>
impl<'a> Iterator for Chars<'a>
impl<'a> Iterator for CharIndices<'a>
impl<'a> Iterator for Bytes<'a>
impl<'a, P> Iterator for Split<'a, P> where P: Pattern<'a>
impl<'a, P> Iterator for RSplit<'a, P> where P: Pattern<'a>, P::Searcher: ReverseSearcher<'a>
impl<'a, P> Iterator for SplitTerminator<'a, P> where P: Pattern<'a>
impl<'a, P> Iterator for RSplitTerminator<'a, P> where P: Pattern<'a>, P::Searcher: ReverseSearcher<'a>
impl<'a, P> Iterator for SplitN<'a, P> where P: Pattern<'a>
impl<'a, P> Iterator for RSplitN<'a, P> where P: Pattern<'a>, P::Searcher: ReverseSearcher<'a>
impl<'a, P> Iterator for MatchIndices<'a, P> where P: Pattern<'a>
impl<'a, P> Iterator for RMatchIndices<'a, P> where P: Pattern<'a>, P::Searcher: ReverseSearcher<'a>
impl<'a, P> Iterator for Matches<'a, P> where P: Pattern<'a>
impl<'a, P> Iterator for RMatches<'a, P> where P: Pattern<'a>, P::Searcher: ReverseSearcher<'a>
impl<'a> Iterator for Lines<'a>
impl<'a> Iterator for LinesAny<'a>
impl<I> Iterator for Box<I> where I: Iterator + ?Sized
impl<'a, T> Iterator for Iter<'a, T>
impl<T> Iterator for IntoIter<T>
impl<'a, T> Iterator for Drain<'a, T> where T: 'a
impl<'a> Iterator for Iter<'a>
impl<'a, T> Iterator for BlockIter<T> where T: Iterator<Item=u32>
impl<'a> Iterator for TwoBitPositions<'a>
impl<'a> Iterator for SetIter<'a>
impl<'a> Iterator for Union<'a>
impl<'a> Iterator for Intersection<'a>
impl<'a> Iterator for Difference<'a>
impl<'a> Iterator for SymmetricDifference<'a>
impl<T> Iterator for RawItems<T>
impl<K, V, E, Impl> Iterator for AbsTraversal<Impl> where Impl: TraversalImpl<Item=(K, V), Edge=E>
impl<K, V, E, T> Iterator for AbsIter<T> where T: DoubleEndedIterator<Item=TraversalItem<K, V, E>> + Traverse<E>
impl<'a, K, V> Iterator for Iter<'a, K, V>
impl<'a, K, V> Iterator for IterMut<'a, K, V>
impl<K, V> Iterator for IntoIter<K, V>
impl<'a, K, V> Iterator for Keys<'a, K, V>
impl<'a, K, V> Iterator for Values<'a, K, V>
impl<'a, K, V> Iterator for Range<'a, K, V>
impl<'a, K, V> Iterator for RangeMut<'a, K, V>
impl<'a, T> Iterator for Iter<'a, T>
impl<T> Iterator for IntoIter<T>
impl<'a, T> Iterator for Range<'a, T>
impl<'a, T> Iterator for Difference<'a, T> where T: Ord
impl<'a, T> Iterator for SymmetricDifference<'a, T> where T: Ord
impl<'a, T> Iterator for Intersection<'a, T> where T: Ord
impl<'a, T> Iterator for Union<'a, T> where T: Ord
impl<E> Iterator for Iter<E> where E: CLike
impl<'a, A> Iterator for Iter<'a, A>
impl<'a, A> Iterator for IterMut<'a, A>
impl<A> Iterator for IntoIter<A>
impl Iterator for ElementSwaps
impl<T> Iterator for Permutations<T> where T: Clone
impl<'a> Iterator for Decompositions<'a>
impl<'a> Iterator for Recompositions<'a>
impl<'a> Iterator for Utf16Units<'a>
impl<'a> Iterator for Drain<'a>
impl<T> Iterator for IntoIter<T>
impl<'a, T> Iterator for Drain<'a, T>
impl<'a, T> Iterator for Iter<'a, T>
impl<'a, T> Iterator for IterMut<'a, T>
impl<T> Iterator for IntoIter<T>
impl<'a, T> Iterator for Drain<'a, T> where T: 'a
impl<'a, V> Iterator for Iter<'a, V>
impl<'a, V> Iterator for IterMut<'a, V>
impl<'a, V> Iterator for Drain<'a, V>
impl<'a, V> Iterator for Keys<'a, V>
impl<'a, V> Iterator for Values<'a, V>
impl<V> Iterator for IntoIter<V>
impl<'a> Iterator for GraphemeIndices<'a>
impl<'a> Iterator for Graphemes<'a>
impl<'a> Iterator for Utf16Items<'a>
impl<I> Iterator for Utf16Encoder<I> where I: Iterator<Item=char>
impl<'a> Iterator for SplitWhitespace<'a>
impl Iterator for ToLowercase
impl Iterator for ToUppercase
impl Iterator for EscapeDefault
impl<'a, K, V> Iterator for Iter<'a, K, V>
impl<'a, K, V> Iterator for IterMut<'a, K, V>
impl<K, V> Iterator for IntoIter<K, V>
impl<'a, K, V> Iterator for Keys<'a, K, V>
impl<'a, K, V> Iterator for Values<'a, K, V>
impl<'a, K, V> Iterator for Drain<'a, K, V>
impl<'a, K> Iterator for Iter<'a, K>
impl<K> Iterator for IntoIter<K>
impl<'a, K> Iterator for Drain<'a, K>
impl<'a, T, S> Iterator for Intersection<'a, T, S> where T: Eq + Hash, S: HashState
impl<'a, T, S> Iterator for Difference<'a, T, S> where T: Eq + Hash, S: HashState
impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S> where T: Eq + Hash, S: HashState
impl<'a, T, S> Iterator for Union<'a, T, S> where T: Eq + Hash, S: HashState
impl Iterator for Vars
impl Iterator for VarsOs
impl<'a> Iterator for SplitPaths<'a>
impl Iterator for Args
impl Iterator for ArgsOs
impl Iterator for ReadDir
impl Iterator for WalkDir
impl<R: Read> Iterator for Bytes<R>
impl<R: Read> Iterator for Chars<R>
impl<B: BufRead> Iterator for Split<B>
impl<B: BufRead> Iterator for Lines<B>
impl<'a> Iterator for Incoming<'a>
impl Iterator for LookupHost
impl<'a> Iterator for Iter<'a>
impl<'a> Iterator for Components<'a>
impl<'a, T> Iterator for Iter<'a, T>
impl<T> Iterator for IntoIter<T>
impl<'a, T, R> Iterator for Generator<'a, T, R> where R: Rng, T: Rand
impl<'a, R> Iterator for AsciiGenerator<'a, R> where R: Rng