Rust Iterator overview

Iterators are a powerful concept in Rust. This website gives an overview and helps you select the best method.

For an introduction, read the chapter in the book. Remember: Iterators (and adapters) are lazy. Creating an iterator does nothing, so you need to consume it to perform the iteration.

Constructors

I want to create an iterator from...

a function
from_fn(next)§

Creates an iterator with the provided closure as its next method.

empty()§

Creates an iterator that yields nothing.

once(element)§

Creates an iterator that yields an element exactly once.

once_with(make)§

Creates an iterator that lazily generates a value exactly once by invoking the provided closure.

repeat(element)§

Creates a new iterator that endlessly repeats a single element.

repeat_n(element, count)§

Creates a new iterator that repeats a single element a given number of times.

repeat_with(repeater)§

Creates a new iterator that repeats elements endlessly by applying the provided closure.

successors(first, next)§

Creates an iterator which, starting from an initial item, computes each successive item from the preceding one.

an array/slice/collection
iter()§

An iterator that borrows the elements

iter_mut()§

An iterator that mutably borrows the elements

into_iter()§

Moves the array/slice/collection, returning an owned iterator over its elements.

a string
chars()§

Returns an iterator over the chars of a string slice.

char_indices()§

Returns an iterator over the chars of a string slice, and their positions.

bytes()§

Returns an iterator over the bytes of a string slice.

lines()§

Returns an iterator over the lines of a string, as string slices.

split(pattern)§

Returns an iterator over substrings of this string slice, separated by characters matched by a pattern.

Also see split_whitespace, split_ascii_whitespace, split_inclusive, rsplit, etc.

matches()§

Returns an iterator over the disjoint matches of a pattern within the given string slice.

Also see rmatches, match_indices, rmatch_indices

a HashMap/BTreeMap
keys()§

An iterator visiting all keys in arbitrary order.

values()§

An iterator visiting all values in arbitrary order.

into_keys()§

Moves the HashMap, returning an iterator over the owned keys in arbitrary order.

into_values()§

Moves the HashMap, returning an iterator over the owned values in arbitrary order.

values_mut()§

An iterator visiting all values mutably in arbitrary order.

CLI arguments
args()§

Returns the arguments that this program was started with (normally passed via the command line).

args_os()§

Returns the arguments that this program was started with as OsStrings (normally passed via the command line).

environment variables
vars()§

Returns an iterator of (variable, value) pairs of strings, for all the environment variables of the current process.

vars_os()§

Returns an iterator of (variable, value) pairs of OsStrings, for all the environment variables of the current process.

a file path
ancestors()§

Produces an iterator over Path and its ancestors.

components()§

Produces an iterator over the Components of the path.

read_dir()§

Returns an iterator over the entries within a directory.

Read/BufRead
bytes()§

Transforms this Read instance to an Iterator over its bytes.

lines()§

Returns an iterator over the lines of this BufRead.

Stdin
lines()§

Consumes this handle and returns an iterator over input lines.

TcpListener
incoming()§

Returns an iterator over the connections being received on this listener.

Adapters
Filter
Remove items from the iterator
filter(predicate)§

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

See also: filter_map

step_by(step)§

Creates an iterator starting at the same point, but stepping by the given amount at each iteration.

skip(n)

Creates an iterator that skips the first n elements.

skip_while(predicate)§

Creates an iterator that skips elements based on a predicate.

take(n)§

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

take_while(predicate)§

Creates an iterator that yields elements while the given predicate returns true.

fuse()§

Creates an iterator which ends after the first None.

Expand
Add items to the iterator
chain(iterator)§

Takes two iterators and creates a new iterator over both in sequence.

cycle()§

Repeats an iterator endlessly.

Transform
Modify the items in the iterator
enumerate()§

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

map(transform)§

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

zip(iterable)§

‘Zips up’ two iterators into a single iterator of pairs.

See also: unzip

flatten()§

Creates an iterator that flattens nested structure.

See also: flat_map

copied()§

Creates an iterator which copies all of its elements.

cloned()§

Creates an iterator which clones all of its elements.

flat_map(transform)§

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

See also: map

filter_map(transform)§

Creates an iterator that both filters and maps.

See also: filter

map_while(transform)§

Creates an iterator that both yields elements based on a predicate and maps.

See also: take_while

scan(init, accumulate)§

An iterator adapter which, like fold, holds internal state, but unlike fold, produces a new iterator.

See also: fold

Misc.
inspect(function)§

Does something with each element of an iterator, passing the value on.

peekable()§

Creates an iterator which can use the peek and peek_mut methods to look at the next element of the iterator without consuming it.

rev()§

Reverses an iterator’s direction.

See also: last, rposition

Consumers
Select
Pick an item from the iterator
next()

Advances the iterator and returns the next value.

last()§

Consumes the iterator, returning the last element.

nth(n)§

Returns the nth element of the iterator.

Search
Find an item matching a predicate
find(predicate)§

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

find_map(transform)§

Applies a function to the elements of the iterator and returns the first non-none result.

See also: map

position(predicate)§

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

rposition(predicate)§

Searches for an element in an iterator from the right, returning its index.

See also: rev

Validate
Check if the iterator meets a certain condition
all(predicate)§

Tests if every element of the iterator matches a predicate.

any(predicate)§

Tests if any element of the iterator matches a predicate.

is_sorted()§

Checks if the elements of this iterator are sorted.

is_sorted_by(compare)§

Checks if the elements of this iterator are sorted using the given comparator function.

is_sorted_by_key(extract_key)§

Checks if the elements of this iterator are sorted using the given key extraction function.

Accumulate
Condense the iterator into a single value
fold(init, accumulate)§

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

See also: try_fold, scan

reduce(reducer)§

Reduces the elements to a single one, by repeatedly applying a reducing operation.

See also: try_reduce

collect::<Collection>()§

Transforms an iterator into a collection.

count()§

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

See also: sum

max()§

Returns the maximum element of an iterator.

max_by(compare)§

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

max_by_key(extract_key)§

Returns the element that gives the maximum value from the specified key extraction function.

min()§

Returns the minimum element of an iterator.

min_by(compare)§

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

min_by_key(extract_key)§

Returns the element that gives the minimum value from the specified key extraction function.

sum()§

Sums the elements of an iterator.

product()§

Iterates over the entire iterator, multiplying all the elements

try_fold(predicate)§

An iterator method that applies a function as long as it returns successfully, producing a single, final value.

See also: fold

try_reduce(reducer)§

Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately.

See also: reduce

unzip()§

Converts an iterator of pairs into a pair of containers.

See also: zip

partition(predicate)§

Consumes an iterator, creating two collections from it.

Compare
Lexicographically compare two iterators
cmp(iterable)§

Lexicographically compares the elements of this Iterator with those of another.

partial_cmp(iterable)§

Lexicographically compares the PartialOrd elements of this Iterator with those of another. The comparison works like short-circuit evaluation.

eq(iterable)§

Determines if the elements of this Iterator are equal to those of another.

ne(iterable)§

Determines if the elements of this Iterator are not equal to those of another.

ge(iterable)§

Determines if the elements of this Iterator are lexicographically greater than or equal to those of another.

gt(iterable)§

Determines if the elements of this Iterator are lexicographically greater than those of another.

le(iterable)§

Determines if the elements of this Iterator are lexicographically less or equal to those of another.

lt(iterable)§

Determines if the elements of this Iterator are lexicographically less than those of another.

Misc.
for_each(function)§

Calls a closure on each element of an iterator.

try_for_each(function)§

An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error.

See also: for_each

Other
by_ref()§

Creates a “by reference” adapter for this instance of Iterator.

size_hint()§

Returns the bounds on the remaining length of the iterator.