Struct ::std::iter::Iterator

Overview

An owning iterator.

Methods

fn next(self) -> Option

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

Basic usage:

let a = [1, 2, 3];

let iter = a.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());

Removes and returns an element from the end of the iterator.

Returns None when there are no more elements.

Examples

Basic usage:

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

let iter = numbers.iter();

assert_eq!(Some(1), iter.next());
assert_eq!(Some(6), iter.next_back());
assert_eq!(Some(5), iter.next_back());
assert_eq!(Some(2), iter.next());
assert_eq!(Some(3), iter.next());
assert_eq!(Some(4), iter.next());
assert_eq!(None, iter.next());
assert_eq!(None, iter.next_back());
fn find(self, find: Function) -> Option

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.

If you need the index of the element, see position().

Examples

Basic usage:

let a = [1, 2, 3];

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

assert_eq!(a.iter().find(|x| x == 5), None);

Stopping at the first true:

let a = [1, 2, 3];

let iter = a.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().

fn any(self, find: Function) -> 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.iter().any(|x| x > 0));

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

Stopping at the first true:

let a = [1, 2, 3];

let iter = a.iter();

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

// we can still use `iter`, as there are more elements.
assert_eq!(iter.next(), Some(2));
fn all(self, find: Function) -> 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.iter().all(|x| x > 0));

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

Stopping at the first false:

let a = [1, 2, 3];

let iter = a.iter();

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

// we can still use `iter`, as there are more elements.
assert_eq!(iter.next(), Some(3));
fn chain(self, other) -> Iterator

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. 🔗

once is commonly used to adapt a single value into a chain of other kinds of iteration.

Examples

Basic usage:

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

let iter = a1.iter().chain(a2.iter());

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

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

let s1 = [1, 2, 3];
let s2 = [4, 5, 6];

let iter = s1.iter().chain(s2);

assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), Some(3));
assert_eq!(iter.next(), Some(4));
assert_eq!(iter.next(), Some(5));
assert_eq!(iter.next(), Some(6));
assert_eq!(iter.next(), None);
fn filter(self, filter: Function) -> Iterator

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.

let a = [0, 1, 2];

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

assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), None);
fn map(self, map: Function) -> Iterator

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

map() transforms one iterator into another. 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 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).iter().map(|x| println!("{}", x));

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

// Instead, use for:
for x in 0..5 {
   println!("{}", x);
}

Creates an iterator that works like map, but flattens nested structure.

The map adapter 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 of mapping, and then flattening as in map(f).flatten().

Another way of thinking about flat_map(): map's closure returns one item for each element, and flat_map()'s closure returns an iterator for each element.

Examples

Basic usage:

let words = ["alpha", "beta", "gamma"];

// chars() returns an iterator
let merged = words.iter().flat_map(|s| s.chars()).collect::<String>();
assert_eq!(merged, "alphabetagamma");

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.

Examples

let a = ['a', 'b', 'c'];

let iter = a.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);
fn peek(self) -> Option

Returns a reference to the next() value without advancing the iterator.

Like next, if there is a value, it is wrapped in a Some(T). But if the iteration is over, None is returned.

Because peek() returns a reference, and many iterators iterate over references, there can be a possibly confusing situation where the return value is a double reference. You can see this effect in the examples below.

Examples

Basic usage:

let xs = [1, 2, 3];

let iter = xs.iter().peekable();

// peek() lets us see into the future
assert_eq!(iter.peek(), Some(1));
assert_eq!(iter.next(), Some(1));

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

// The iterator does not advance even if we `peek` multiple times
assert_eq!(iter.peek(), Some(3));
assert_eq!(iter.peek(), Some(3));

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

// After the iterator is finished, so is `peek()`
assert_eq!(iter.peek(), None);
assert_eq!(iter.next(), None);

Creates an iterator which can use the peek method 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 peek are called for the first time: In order to retrieve the next element, next is called on the underlying iterator, hence any side effects (i.e. anything other than fetching the next value) of the next method will occur.

Examples

Basic usage:

let xs = [1, 2, 3];

let iter = xs.iter().peekable();

// peek() lets us see into the future
assert_eq!(iter.peek(), Some(1));
assert_eq!(iter.next(), Some(1));

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

// we can peek() multiple times, the iterator won't advance
assert_eq!(iter.peek(), Some(3));
assert_eq!(iter.peek(), Some(3));

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

// after the iterator is finished, so is peek()
assert_eq!(iter.peek(), None);
assert_eq!(iter.next(), None);
fn sum<i64>(self) -> i64

Sums the elements of an iterator.

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

An empty iterator returns the zero value of the type.

sum() can be used to sum numerical built-in types, such as int, float and u8. The first element returned by the iterator determines the type being summed.

Panics

When calling sum() and a primitive integer type is being returned, this method will panic if the computation overflows.

Examples

Basic usage:

let a = [1i64, 2i64, 3i64];
let sum = a.iter().sum::<i64>();

assert_eq!(sum, 6i64);
fn sum<u8>(self) -> u8

Sums the elements of an iterator.

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

An empty iterator returns the zero value of the type.

sum() can be used to sum numerical built-in types, such as int, float and u8. The first element returned by the iterator determines the type being summed.

Panics

When calling sum() and a primitive integer type is being returned, this method will panic if the computation overflows.

Examples

Basic usage:

let a = [1u8, 2u8, 3u8];
let sum = a.iter().sum::<u8>();

assert_eq!(sum, 6u8);
fn sum<f64>(self) -> f64

Sums the elements of an iterator.

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

An empty iterator returns the zero value of the type.

sum() can be used to sum numerical built-in types, such as int, float and u8. The first element returned by the iterator determines the type being summed.

Panics

When calling sum() and a primitive integer type is being returned, this method will panic if the computation overflows.

Examples

Basic usage:

let a = [1f64, 2f64, 3f64];
let sum = a.iter().sum::<f64>();

assert_eq!(sum, 6f64);
fn product<i64>(self) -> i64

Iterates over the entire iterator, multiplying all the elements

An empty iterator returns the one value of the type.

sum() can be used to sum numerical built-in types, such as int, float and u8. The first element returned by the iterator determines the type being multiplied.

Panics

When calling product() and a primitive integer type is being returned, method will panic if the computation overflows.

Examples

fn factorial(n) {
   (1i64..=n).iter().product::<i64>()
}

assert_eq!(factorial(0i64), 1i64);
assert_eq!(factorial(1i64), 1i64);
assert_eq!(factorial(5i64), 120i64);
fn product<u8>(self) -> u8

Iterates over the entire iterator, multiplying all the elements

An empty iterator returns the one value of the type.

sum() can be used to sum numerical built-in types, such as int, float and u8. The first element returned by the iterator determines the type being multiplied.

Panics

When calling product() and a primitive integer type is being returned, method will panic if the computation overflows.

Examples

fn factorial(n) {
   (1u8..=n).iter().product::<u8>()
}

assert_eq!(factorial(0u8), 1u8);
assert_eq!(factorial(1u8), 1u8);
assert_eq!(factorial(5u8), 120u8);
fn product<f64>(self) -> f64

Iterates over the entire iterator, multiplying all the elements

An empty iterator returns the one value of the type.

sum() can be used to sum numerical built-in types, such as int, float and u8. The first element returned by the iterator determines the type being multiplied.

Panics

When calling product() and a primitive integer type is being returned, method will panic if the computation overflows.

Examples

fn factorial(n) {
   (1..=n).iter().map(|n| n as f64).product::<f64>()
}

assert_eq!(factorial(0), 1f64);
assert_eq!(factorial(1), 1f64);
assert_eq!(factorial(5), 120f64);
fn fold(self, accumulator, f: Function)

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:

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

let zero = "0";

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 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);
fn reduce(self, f: Function) -> Option

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 = (1..10).iter().reduce(|acc, e| acc + e).unwrap();
assert_eq!(reduced, 45);

// Which is equivalent to doing it with `fold`:
let folded = (1..10).iter().fold(0, |acc, e| acc + e);
assert_eq!(reduced, folded);
fn rev(self) -> Iterator

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 double-ended iterators.

Examples

let a = [1, 2, 3];

let iter = a.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);

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]<[i64]>. A [None] here means that either there is no known upper bound, or the upper bound is larger than [i64].

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 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).iter().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).iter().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..).iter();

assert_eq!((i64::MAX, None), iter.size_hint());
fn skip(self, n: i64) -> Iterator

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.

Examples

Basic usage:

let a = [1, 2, 3];

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

assert_eq!(iter.next(), Some(3));
assert_eq!(iter.next(), None);
fn take(self, n: i64) -> Iterator

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 iter = a.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 iter = (0..).iter().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 iter = v.iter().take(5);
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), None);
fn count(self) -> i64

Consumes the iterator, counting the number of iterations and returning it.

This method will call next repeatedly until [None] is encountered, returning the number of times it saw [Some]. Note that next has 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 [i64::MAX] elements panics.

Panics

This function might panic if the iterator has more than [i64::MAX] elements.

Examples

Basic usage:

let a = [1, 2, 3];
assert_eq!(a.iter().count(), 3);

let a = [1, 2, 3, 4, 5];
assert_eq!(a.iter().count(), 5);
fn collect<Vec>(self) -> Vec

Collect the iterator as a [Vec].

Examples

use std::iter::range;

assert_eq!((0..3).iter().collect::<Vec>(), [0, 1, 2]);

Collect the iterator as a [VecDeque].

Examples

use std::collections::VecDeque;

assert_eq!((0..3).iter().collect::<VecDeque>(), VecDeque::from([0, 1, 2]));

Collect the iterator as a [HashSet].

Examples

use std::collections::HashSet;

assert_eq!((0..3).iter().collect::<HashSet>(), HashSet::from([0, 1, 2]));

Collect the iterator as a [HashMap].

Examples

use std::collections::HashMap;

let actual = (0..3).iter().map(|n| (n, n.to_string())).collect::<HashMap>();
let expected = HashMap::from([(0, "0"), (1, "1"), (2, "2")]);
assert_eq!(actual, expected);

Collect the iterator as a [Tuple].

Examples

assert_eq!((0..3).iter().collect::<Tuple>(), (0, 1, 2));

Collect the iterator as an [Object].

Examples

assert_eq!([("first", 1), ("second", 2)].iter().collect::<Object>(), #{first: 1, second: 2});

Collect the iterator as a [String].

Examples

assert_eq!(["first", "second"].iter().collect::<String>(), "firstsecond");

Protocols

protocol next

Allows iteration to be advanced for the type, this is used for iterators.

protocol into_iter
for item in value { }

Allows the value to be converted into an iterator in a for-loop.