Iterator

Trait Iterator 

1.6.0 · Source
pub trait Iterator {
    type Item;

Show 24 methods // Required method fn next(&mut self) -> Option<Self::Item>; // Provided methods fn size_hint(&self) -> (usize, Option<usize>) { ... } fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> { ... } fn nth(&mut self, n: usize) -> Option<Self::Item> { ... } fn step_by(self, step: usize) -> StepBy<Self> where Self: Sized { ... } fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where Self: Sized, U: IntoIterator { ... } fn map<B, F>(self, f: F) -> Map<Self, F> where Self: Sized, F: FnMut(Self::Item) -> B { ... } fn for_each<F>(self, f: F) where Self: Sized, F: FnMut(Self::Item) { ... } fn filter<P>(self, predicate: P) -> Filter<Self, P> where Self: Sized, P: FnMut(&Self::Item) -> bool { ... } fn enumerate(self) -> Enumerate<Self> where Self: Sized { ... } fn skip(self, n: usize) -> Skip<Self> where Self: Sized { ... } fn take(self, n: usize) -> Take<Self> where Self: Sized { ... } fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized { ... } fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R where Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Output = B> { ... } fn fold<B, F>(self, init: B, f: F) -> B where Self: Sized, F: FnMut(B, Self::Item) -> B { ... } fn reduce<F>(self, f: F) -> Option<Self::Item> where Self: Sized, F: FnMut(Self::Item, Self::Item) -> Self::Item { ... } fn all<F>(&mut self, f: F) -> bool where Self: Sized, F: FnMut(Self::Item) -> bool { ... } fn any<F>(&mut self, f: F) -> bool where Self: Sized, F: FnMut(Self::Item) -> bool { ... } fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where Self: Sized, P: FnMut(&Self::Item) -> bool { ... } fn position<P>(&mut self, predicate: P) -> Option<usize> where Self: Sized, P: FnMut(Self::Item) -> bool { ... } fn max_by<F>(self, compare: F) -> Option<Self::Item> where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering { ... } fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator { ... } fn cloned<'a, T>(self) -> Cloned<Self> where T: Clone + 'a, Self: Sized + Iterator<Item = &'a T> { ... } fn sum<S>(self) -> S where Self: Sized, S: Sum<Self::Item> { ... }
}
Expand description

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.

Required Associated Types§

1.0.0 · Source

type Item

The type of the elements being iterated over.

Required Methods§

1.0.0 · Source

fn next(&mut self) -> Option<Self::Item>

Advances the iterator and returns the next value.

Returns None when iteration is finished. Individual iterator implementations may choose to resume iteration, and so calling next() again may or may not eventually start returning Some(Item) again at some point.

§Examples
let a = [1, 2, 3];

let mut iter = a.into_iter();

// A call to next() returns the next value...
assert_eq!(Some(1), iter.next());
assert_eq!(Some(2), iter.next());
assert_eq!(Some(3), iter.next());

// ... and then None once it's over.
assert_eq!(None, iter.next());

// More calls may or may not return `None`. Here, they always will.
assert_eq!(None, iter.next());
assert_eq!(None, iter.next());

Provided Methods§

1.0.0 · Source

fn size_hint(&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>. A None here means that either there is no known upper bound, or the upper bound is larger than usize.

§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 of size_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 = [1, 2, 3];
let mut iter = a.iter();

assert_eq!((3, Some(3)), iter.size_hint());
let _ = iter.next();
assert_eq!((2, Some(2)), iter.size_hint());

A more complex example:

// The even numbers in the range of zero to nine.
let iter = (0..10).filter(|x| x % 2 == 0);

// We might iterate from zero to ten times. Knowing that it's five
// exactly wouldn't be possible without executing filter().
assert_eq!((0, Some(10)), iter.size_hint());

// Let's add five more numbers with chain()
let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);

// now both bounds are increased by five
assert_eq!((5, Some(15)), iter.size_hint());

Returning None for an upper bound:

// an infinite iterator has no upper bound
// and the maximum possible lower bound
let iter = 0..;

assert_eq!((usize::MAX, None), iter.size_hint());
Source

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

🔬This is a nightly-only experimental API. (iter_advance_by #77404)

Advances the iterator by n elements.

This method will eagerly skip n elements by calling next up to n times until None is encountered.

advance_by(n) will return Ok(()) if the iterator successfully advances by n elements, or a Err(NonZero<usize>) with value k if None is encountered, where k is remaining number of steps that could not be advanced because the iterator ran out. If self is empty and n is non-zero, then this returns Err(n). Otherwise, k is always less than n.

Calling advance_by(0) can do meaningful work, for example Flatten can advance its outer iterator until it finds an inner iterator that is not empty, which then often allows it to return a more accurate size_hint() than in its initial state.

§Examples
#![feature(iter_advance_by)]

use std::num::NonZero;

let a = [1, 2, 3, 4];
let mut iter = a.into_iter();

assert_eq!(iter.advance_by(2), Ok(()));
assert_eq!(iter.next(), Some(3));
assert_eq!(iter.advance_by(0), Ok(()));
assert_eq!(iter.advance_by(100), Err(NonZero::new(99).unwrap())); // only `4` was skipped
1.0.0 · Source

fn nth(&mut self, n: usize) -> Option<Self::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 return None if n is greater than or equal to the length of the iterator.

§Examples

Basic usage:

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

Calling nth() multiple times doesn’t rewind the iterator:

let a = [1, 2, 3];

let mut iter = a.into_iter();

assert_eq!(iter.nth(1), Some(2));
assert_eq!(iter.nth(1), None);

Returning None if there are less than n + 1 elements:

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

fn step_by(self, step: usize) -> StepBy<Self>
where Self: Sized,

Creates 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. StepBy behaves like the sequence self.next(), self.nth(step-1), self.nth(step-1), …, but is also free to behave like the sequence advance_n_and_return_first(&mut self, step), advance_n_and_return_first(&mut self, step), … Which way is used may change for some iterators for performance reasons. The second way will advance the iterator earlier and may consume more items.

advance_n_and_return_first is the equivalent of:

fn advance_n_and_return_first<I>(iter: &mut I, n: usize) -> Option<I::Item>
where
    I: Iterator,
{
    let next = iter.next();
    if n > 1 {
        iter.nth(n - 2);
    }
    next
}
§Panics

The method will panic if the given step is 0.

§Examples
let a = [0, 1, 2, 3, 4, 5];
let mut iter = a.into_iter().step_by(2);

assert_eq!(iter.next(), Some(0));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), Some(4));
assert_eq!(iter.next(), None);
1.0.0 · Source

fn zip<U>(self, other: U) -> Zip<Self, U::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, next from the zipped iterator will return None. 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(s2);

assert_eq!(iter.next(), Some(('a', 'd')));
assert_eq!(iter.next(), Some(('b', 'e')));
assert_eq!(iter.next(), Some(('c', 'f')));
assert_eq!(iter.next(), None);

Since the argument to zip() uses IntoIterator, we can pass anything that can be converted into an Iterator, not just an Iterator itself. For example, arrays ([T]) implement IntoIterator, and so can be passed to zip() directly:

let a1 = [1, 2, 3];
let a2 = [4, 5, 6];

let mut iter = a1.into_iter().zip(a2);

assert_eq!(iter.next(), Some((1, 4)));
assert_eq!(iter.next(), Some((2, 5)));
assert_eq!(iter.next(), Some((3, 6)));
assert_eq!(iter.next(), None);

zip() is often used to zip an infinite iterator to a finite one. This works because the finite iterator will eventually return None, ending the zipper. Zipping with (0..) can look a lot like enumerate:

let enumerate: Vec<_> = "foo".chars().enumerate().collect();

let zipper: Vec<_> = (0..).zip("foo".chars()).collect();

assert_eq!((0, 'f'), enumerate[0]);
assert_eq!((0, 'f'), zipper[0]);

assert_eq!((1, 'o'), enumerate[1]);
assert_eq!((1, 'o'), zipper[1]);

assert_eq!((2, 'o'), enumerate[2]);
assert_eq!((2, 'o'), zipper[2]);

If both iterators have roughly equivalent syntax, it may be more readable to use zip:

use std::iter::zip;

let a = [1, 2, 3];
let b = [2, 3, 4];

let mut zipped = zip(
    a.into_iter().map(|x| x * 2).skip(1),
    b.into_iter().map(|x| x * 2).skip(1),
);

assert_eq!(zipped.next(), Some((4, 6)));
assert_eq!(zipped.next(), Some((6, 8)));
assert_eq!(zipped.next(), None);

compared to:

let mut zipped = a
    .into_iter()
    .map(|x| x * 2)
    .skip(1)
    .zip(b.into_iter().map(|x| x * 2).skip(1));
1.0.0 · Source

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

Takes a closure and creates an iterator which calls that closure on each element.

map() transforms one iterator into another, by means of its argument: something that implements FnMut. 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 type A, and you want an iterator of some other type B, you can use map(), passing a closure that takes an A and returns a B.

map() is conceptually similar to a for loop. However, as map() 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 use for than map().

§Examples

Basic usage:

let a = [1, 2, 3];

let mut iter = a.iter().map(|x| 2 * x);

assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), Some(4));
assert_eq!(iter.next(), Some(6));
assert_eq!(iter.next(), None);

If you’re doing some sort of side effect, prefer for to map():

// don't do this:
(0..5).map(|x| println!("{x}"));

// it won't even execute, as it is lazy. Rust will warn you about this.

// Instead, use a for-loop:
for x in 0..5 {
    println!("{x}");
}
1.21.0 · Source

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

Calls a closure on each element of an iterator.

This is equivalent to using a for loop on the iterator, although break and continue are not possible from a closure. It’s generally more idiomatic to use a for loop, but for_each may be more legible when processing items at the end of longer iterator chains. In some cases for_each may also be faster than a loop, because it will use internal iteration on adapters like Chain.

§Examples

Basic usage:

use std::sync::mpsc::channel;

let (tx, rx) = channel();
(0..5).map(|x| x * 2 + 1)
      .for_each(move |x| tx.send(x).unwrap());

let v: Vec<_> = rx.iter().collect();
assert_eq!(v, vec![1, 3, 5, 7, 9]);

For such a small example, a for loop may be cleaner, but for_each might be preferable to keep a functional style with longer iterators:

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

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

Creates an iterator which uses a closure to determine if an element should be yielded.

Given an element the closure must return true or false. The returned iterator will yield only the elements for which the closure returns true.

§Examples

Basic usage:

let a = [0i32, 1, 2];

let mut iter = a.into_iter().filter(|x| x.is_positive());

assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), None);

Because the closure passed 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 = &[0, 1, 2];

let mut iter = s.iter().filter(|x| **x > 1); // needs two *s!

assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), None);

It’s common to instead use destructuring on the argument to strip away one:

let s = &[0, 1, 2];

let mut iter = s.iter().filter(|&x| *x > 1); // both & and *

assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), None);

or both:

let s = &[0, 1, 2];

let mut iter = s.iter().filter(|&&x| x > 1); // two &s

assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), None);

of these layers.

Note that iter.filter(f).next() is equivalent to iter.find(f).

1.0.0 · Source

fn enumerate(self) -> Enumerate<Self>
where Self: Sized,

Creates an iterator which gives the current iteration count as well as the next value.

The iterator returned 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 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 = ['a', 'b', 'c'];

let mut iter = a.into_iter().enumerate();

assert_eq!(iter.next(), Some((0, 'a')));
assert_eq!(iter.next(), Some((1, 'b')));
assert_eq!(iter.next(), Some((2, 'c')));
assert_eq!(iter.next(), None);
1.0.0 · Source

fn skip(self, n: usize) -> Skip<Self>
where Self: Sized,

Creates an iterator that skips the first n elements.

skip(n) skips elements until n elements 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 nth method.

§Examples
let a = [1, 2, 3];

let mut iter = a.into_iter().skip(2);

assert_eq!(iter.next(), Some(3));
assert_eq!(iter.next(), None);
1.0.0 · Source

fn take(self, n: usize) -> Take<Self>
where Self: Sized,

Creates an iterator that yields the first n elements, or fewer if the underlying iterator ends sooner.

take(n) yields elements until n elements are yielded or the end of the iterator is reached (whichever happens first). The returned iterator is a prefix of length n if the original iterator contains at least n elements, otherwise it contains all of the (fewer than n) elements of the original iterator.

§Examples

Basic usage:

let a = [1, 2, 3];

let mut iter = a.into_iter().take(2);

assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), None);

take() is often used with an infinite iterator, to make it finite:

let mut iter = (0..).take(3);

assert_eq!(iter.next(), Some(0));
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), None);

If less than n elements are available, take will limit itself to the size of the underlying iterator:

let v = [1, 2];
let mut iter = v.into_iter().take(5);
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), None);

Use by_ref to take from the iterator without consuming it, and then continue using the original iterator:

let mut words = ["hello", "world", "of", "Rust"].into_iter();

// Take the first two words.
let hello_world: Vec<_> = words.by_ref().take(2).collect();
assert_eq!(hello_world, vec!["hello", "world"]);

// Collect the rest of the words.
// We can only do this because we used `by_ref` earlier.
let of_rust: Vec<_> = words.collect();
assert_eq!(of_rust, vec!["of", "Rust"]);
1.0.0 · Source

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

Transforms an iterator into a collection.

collect() can take anything iterable, and turn it into a relevant collection. This is one of the more powerful methods in the standard library, used in a variety of contexts.

The most basic pattern in which collect() is used is to turn one collection into another. You take a collection, call iter on it, do a bunch of transformations, and then collect() at the end.

collect() can also create instances of types that are not typical collections. For example, a String can be built from chars, and an iterator of Result<T, E> items can be collected into Result<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 = [1, 2, 3];

let doubled: Vec<i32> = a.iter()
                         .map(|x| x * 2)
                         .collect();

assert_eq!(vec![2, 4, 6], doubled);

Note that we needed the : Vec<i32> on the left-hand side. This is because we could collect into, for example, a VecDeque<T> instead:

use std::collections::VecDeque;

let a = [1, 2, 3];

let doubled: VecDeque<i32> = a.iter().map(|x| x * 2).collect();

assert_eq!(2, doubled[0]);
assert_eq!(4, doubled[1]);
assert_eq!(6, doubled[2]);

Using the ‘turbofish’ instead of annotating doubled:

let a = [1, 2, 3];

let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();

assert_eq!(vec![2, 4, 6], doubled);

Because collect() only cares about what you’re collecting into, you can still use a partial type hint, _, with the turbofish:

let a = [1, 2, 3];

let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();

assert_eq!(vec![2, 4, 6], doubled);

Using collect() to make a String:

let chars = ['g', 'd', 'k', 'k', 'n'];

let hello: String = chars.into_iter()
    .map(|x| x as u8)
    .map(|x| (x + 1) as char)
    .collect();

assert_eq!("hello", hello);

If you have a list of Result<T, E>s, you can use collect() to see if any of them failed:

let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];

let result: Result<Vec<_>, &str> = results.into_iter().collect();

// gives us the first error
assert_eq!(Err("nope"), result);

let results = [Ok(1), Ok(3)];

let result: Result<Vec<_>, &str> = results.into_iter().collect();

// gives us the list of answers
assert_eq!(Ok(vec![1, 3]), result);
1.27.0 · Source

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

An iterator method that applies a function as long as it 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 for loop 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 self method, so iteration needs to be resumable after hitting an error here.

§Examples

Basic usage:

let a = [1, 2, 3];

// the checked sum of all of the elements of the array
let sum = a.into_iter().try_fold(0i8, |acc, x| acc.checked_add(x));

assert_eq!(sum, Some(6));

Short-circuiting:

let a = [10, 20, 30, 100, 40, 50];
let mut iter = a.into_iter();

// This sum overflows when adding the 100 element
let sum = iter.try_fold(0i8, |acc, x| acc.checked_add(x));
assert_eq!(sum, None);

// Because it short-circuited, the remaining elements are still
// available through the iterator.
assert_eq!(iter.len(), 2);
assert_eq!(iter.next(), Some(40));

While you cannot break from a closure, the ControlFlow type allows a similar idea:

use std::ops::ControlFlow;

let triangular = (1..30).try_fold(0_i8, |prev, x| {
    if let Some(next) = prev.checked_add(x) {
        ControlFlow::Continue(next)
    } else {
        ControlFlow::Break(prev)
    }
});
assert_eq!(triangular, ControlFlow::Break(120));

let triangular = (1..30).try_fold(0_u64, |prev, x| {
    if let Some(next) = prev.checked_add(x) {
        ControlFlow::Continue(next)
    } else {
        ControlFlow::Break(prev)
    }
});
assert_eq!(triangular, ControlFlow::Continue(435));
1.0.0 · Source

fn fold<B, F>(self, init: B, f: F) -> B
where Self: Sized, F: FnMut(B, Self::Item) -> B,

Folds every element into an accumulator by applying an operation, returning the final result.

fold() takes two arguments: an initial value, and a closure with 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 of fold(), 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 for loop implementation.

In particular, try to have this call fold() on the internal parts from which this iterator is composed.

§Examples

Basic usage:

let a = [1, 2, 3];

// the sum of all of the elements of the array
let sum = a.iter().fold(0, |acc, x| acc + x);

assert_eq!(sum, 6);

Let’s walk through each step of the iteration here:

elementaccxresult
0
1011
2123
3336

And so, our final result, 6.

This example demonstrates the left-associative nature of fold(): it builds a string, starting with an initial value and continuing with each element from the front until the back:

let numbers = [1, 2, 3, 4, 5];

let zero = "0".to_string();

let result = numbers.iter().fold(zero, |acc, &x| {
    format!("({acc} + {x})")
});

assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");

It’s common for people who haven’t used iterators a lot to use a for loop with a list of things to build up a result. Those can be turned into fold()s:

let numbers = [1, 2, 3, 4, 5];

let mut result = 0;

// for loop:
for i in &numbers {
    result = result + i;
}

// fold:
let result2 = numbers.iter().fold(0, |acc, &x| acc + x);

// they're the same
assert_eq!(result, result2);
1.51.0 · Source

fn reduce<F>(self, f: F) -> Option<Self::Item>
where Self: Sized, F: FnMut(Self::Item, Self::Item) -> Self::Item,

Reduces the elements to a single one, by repeatedly applying a 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 = (1..10).reduce(|acc, e| acc + e).unwrap_or(0);
assert_eq!(reduced, 45);

// Which is equivalent to doing it with `fold`:
let folded: i32 = (1..10).fold(0, |acc, e| acc + e);
assert_eq!(reduced, folded);
1.0.0 · Source

fn all<F>(&mut self, f: F) -> bool
where Self: Sized, F: FnMut(Self::Item) -> bool,

Tests if every element of the iterator matches a predicate.

all() takes a closure that returns true or false. It applies this closure to each element of the iterator, and if they all return true, then so does all(). If any of them return false, it returns false.

all() is short-circuiting; in other words, it will stop processing as soon as it finds a false, given that no matter what else happens, the result will also be false.

An empty iterator returns true.

§Examples

Basic usage:

let a = [1, 2, 3];

assert!(a.into_iter().all(|x| x > 0));

assert!(!a.into_iter().all(|x| x > 2));

Stopping at the first false:

let a = [1, 2, 3];

let mut iter = a.into_iter();

assert!(!iter.all(|x| x != 2));

// we can still use `iter`, as there are more elements.
assert_eq!(iter.next(), Some(3));
1.0.0 · Source

fn any<F>(&mut self, f: F) -> bool
where Self: Sized, F: FnMut(Self::Item) -> bool,

Tests if any element of the iterator matches a predicate.

any() takes a closure that returns true or false. It applies this closure to each element of the iterator, and if any of them return true, then so does any(). If they all return false, it returns false.

any() is short-circuiting; in other words, it will stop processing as soon as it finds a true, given that no matter what else happens, the result will also be true.

An empty iterator returns false.

§Examples

Basic usage:

let a = [1, 2, 3];

assert!(a.into_iter().any(|x| x > 0));

assert!(!a.into_iter().any(|x| x > 5));

Stopping at the first true:

let a = [1, 2, 3];

let mut iter = a.into_iter();

assert!(iter.any(|x| x != 2));

// we can still use `iter`, as there are more elements.
assert_eq!(iter.next(), Some(2));
1.0.0 · Source

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

Searches for an element of an iterator that satisfies a predicate.

find() takes a closure that returns true or false. It applies this closure to each element of the iterator, and if any of them return true, then find() returns Some(element). If they all return false, it returns None.

find() is short-circuiting; in other words, it will stop processing as soon as the closure returns true.

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 = [1, 2, 3];

assert_eq!(a.into_iter().find(|&x| x == 2), Some(2));
assert_eq!(a.into_iter().find(|&x| x == 5), None);

Stopping at the first true:

let a = [1, 2, 3];

let mut iter = a.into_iter();

assert_eq!(iter.find(|&x| x == 2), Some(2));

// we can still use `iter`, as there are more elements.
assert_eq!(iter.next(), Some(3));

Note that iter.find(f) is equivalent to iter.filter(f).next().

1.0.0 · Source

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

Searches for an element in an iterator, returning its index.

position() takes a closure that returns true or false. It applies this closure to each element of the iterator, and if one of them returns true, then position() returns Some(index). If all of them return false, it returns None.

position() is short-circuiting; in other words, it will stop processing as soon as it finds a true.

§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 overflow checks are enabled, a panic is guaranteed.

§Panics

This function might panic if the iterator has more than usize::MAX non-matching elements.

§Examples

Basic usage:

let a = [1, 2, 3];

assert_eq!(a.into_iter().position(|x| x == 2), Some(1));

assert_eq!(a.into_iter().position(|x| x == 5), None);

Stopping at the first true:

let a = [1, 2, 3, 4];

let mut iter = a.into_iter();

assert_eq!(iter.position(|x| x >= 2), Some(1));

// we can still use `iter`, as there are more elements.
assert_eq!(iter.next(), Some(3));

// The returned index depends on iterator state
assert_eq!(iter.position(|x| x == 4), Some(0));
1.15.0 · Source

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

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

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

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

fn rev(self) -> Rev<Self>
where Self: Sized + DoubleEndedIterator,

Reverses 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 on DoubleEndedIterators.

§Examples
let a = [1, 2, 3];

let mut iter = a.into_iter().rev();

assert_eq!(iter.next(), Some(3));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), Some(1));

assert_eq!(iter.next(), None);
1.0.0 · Source

fn cloned<'a, T>(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 over T.

There is no guarantee whatsoever about the clone method actually being called or optimized away. So code should not depend on either.

§Examples

Basic usage:

let a = [1, 2, 3];

let v_cloned: Vec<_> = a.iter().cloned().collect();

// cloned is the same as .map(|&x| x), for integers
let v_map: Vec<_> = a.iter().map(|&x| x).collect();

assert_eq!(v_cloned, [1, 2, 3]);
assert_eq!(v_map, [1, 2, 3]);

To get the best performance, try to clone late:

let a = [vec![0_u8, 1, 2], vec![3, 4], vec![23]];
// don't do this:
let slower: Vec<_> = a.iter().cloned().filter(|s| s.len() == 1).collect();
assert_eq!(&[vec![23]], &slower[..]);
// instead call `cloned` late
let faster: Vec<_> = a.iter().filter(|s| s.len() == 1).cloned().collect();
assert_eq!(&[vec![23]], &faster[..]);
1.11.0 · Source

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

Sums the elements of an iterator.

Takes each element, adds them together, and returns the result.

An empty iterator returns the additive identity (“zero”) of the type, which is 0 for integers and -0.0 for floats.

sum() can be used to sum any type implementing Sum, including [Option][Option::sum] and [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 = [1, 2, 3];
let sum: i32 = a.iter().sum();

assert_eq!(sum, 6);

let b: Vec<f32> = vec![];
let sum: f32 = b.iter().sum();
assert_eq!(sum, -0.0_f32);

Implementors§

1.0.0 · Source§

impl<'a> Iterator for Chars<'a>

1.1.0 · Source§

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

Source§

type Item = T

1.0.0 · Source§

impl<'a, T> Iterator for Chunks<'a, T>

Source§

type Item = &'a [T]

1.31.0 · Source§

impl<'a, T> Iterator for ChunksExact<'a, T>

Source§

type Item = &'a [T]

1.31.0 · Source§

impl<'a, T> Iterator for ChunksExactMut<'a, T>

Source§

type Item = &'a mut [T]

1.0.0 · Source§

impl<'a, T> Iterator for ChunksMut<'a, T>

Source§

type Item = &'a mut [T]

1.0.0 · Source§

impl<'a, T> Iterator for Iter<'a, T>

1.0.0 · Source§

impl<'a, T> Iterator for IterMut<'a, T>

1.0.0 · Source§

impl<'a, T> Iterator for Windows<'a, T>

Source§

type Item = &'a [T]

1.0.0 · Source§

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

Source§

type Item = A

1.0.0 · Source§

impl<A, B> Iterator for Zip<A, B>
where A: Iterator, B: Iterator,

Source§

type Item = (<A as Iterator>::Item, <B as Iterator>::Item)

1.0.0 · Source§

impl<A: Step> Iterator for Range<A>

Source§

type Item = A

1.0.0 · Source§

impl<B, I: Iterator, F> Iterator for Map<I, F>
where F: FnMut(I::Item) -> B,

Source§

type Item = B

1.0.0 · Source§

impl<I> Iterator for Enumerate<I>
where I: Iterator,

Source§

type Item = (usize, <I as Iterator>::Item)

1.0.0 · Source§

impl<I> Iterator for Rev<I>

Source§

type Item = <I as Iterator>::Item

1.0.0 · Source§

impl<I> Iterator for Skip<I>
where I: Iterator,

Source§

type Item = <I as Iterator>::Item

1.28.0 · Source§

impl<I> Iterator for StepBy<I>
where I: Iterator,

Source§

type Item = <I as Iterator>::Item

1.0.0 · Source§

impl<I> Iterator for Take<I>
where I: Iterator,

Source§

type Item = <I as Iterator>::Item

1.0.0 · Source§

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

Implements Iterator for mutable references to iterators, such as those produced by [Iterator::by_ref].

This implementation passes all method calls on to the original iterator.

Source§

type Item = <I as Iterator>::Item

1.0.0 · Source§

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

Source§

type Item = <I as Iterator>::Item

1.80.0 · Source§

impl<T> !Iterator for [T]

1.34.0 · Source§

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

Source§

type Item = T

1.40.0 · Source§

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

Source§

type Item = T