Struct ::std::iter::Iterator
An owning iterator.
Methods
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 = ;
let iter = a.iter;
// A call to next() returns the next value...
assert_eq!;
assert_eq!;
assert_eq!;
// ... and then None once it's over.
assert_eq!;
// More calls may or may not return `None`. Here, they always will.
assert_eq!;
assert_eq!;
Removes and returns an element from the end of the iterator.
Returns None
when there are no more elements.
Examples
Basic usage:
let numbers = ;
let iter = numbers.iter;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
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 = ;
assert_eq!;
assert_eq!;
Stopping at the first true
:
let a = ;
let iter = a.iter;
assert_eq!;
// we can still use `iter`, as there are more elements.
assert_eq!;
Note that iter.find(f)
is equivalent to iter.filter(f).next()
.
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 = ;
assert!;
assert!;
Stopping at the first true
:
let a = ;
let iter = a.iter;
assert!;
// we can still use `iter`, as there are more elements.
assert_eq!;
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 = ;
assert!;
assert!;
Stopping at the first false
:
let a = ;
let iter = a.iter;
assert!;
// we can still use `iter`, as there are more elements.
assert_eq!;
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 = ;
let a2 = ;
let iter = a1.iter .chain;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
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 = ;
let s2 = ;
let iter = s1.iter .chain;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
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 = ;
let iter = a.iter .filter;
assert_eq!;
assert_eq!;
assert_eq!;
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 = ;
let iter = a.iter .map;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
If you're doing some sort of side effect, prefer for
to map()
:
// don't do this:
.iter .map;
// it won't even execute, as it is lazy. Rust will warn you about this.
// Instead, use for:
for x in 0..5
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 map
ping, and then flatten
ing 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 = ;
// chars() returns an iterator
let merged = words.iter .flat_map .;
assert_eq!;
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 = ;
let iter = a.iter .enumerate;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
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 = ;
let iter = xs.iter .peekable;
// peek() lets us see into the future
assert_eq!;
assert_eq!;
assert_eq!;
// The iterator does not advance even if we `peek` multiple times
assert_eq!;
assert_eq!;
assert_eq!;
// After the iterator is finished, so is `peek()`
assert_eq!;
assert_eq!;
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 = ;
let iter = xs.iter .peekable;
// peek() lets us see into the future
assert_eq!;
assert_eq!;
assert_eq!;
// we can peek() multiple times, the iterator won't advance
assert_eq!;
assert_eq!;
assert_eq!;
// after the iterator is finished, so is peek()
assert_eq!;
assert_eq!;
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 = ;
let sum = a.iter .;
assert_eq!;
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 = ;
let sum = a.iter .;
assert_eq!;
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 = ;
let sum = a.iter .;
assert_eq!;
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
assert_eq!;
assert_eq!;
assert_eq!;
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
assert_eq!;
assert_eq!;
assert_eq!;
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
assert_eq!;
assert_eq!;
assert_eq!;
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 = ;
// the sum of all of the elements of the array
let sum = a.iter .fold;
assert_eq!;
Let's walk through each step of the iteration here:
| element | acc | x | result | |---------|-----|---|--------| | | 0 | | | | 1 | 0 | 1 | 1 | | 2 | 1 | 2 | 3 | | 3 | 3 | 3 | 6 |
And so, our final result, 6
.
This example demonstrates the left-associative nature of fold()
: it builds a string, starting with an initial value and continuing with each element from the front until the back:
let numbers = ;
let zero = "0";
let result = numbers.iter .fold;
assert_eq!;
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 = ;
let result = 0;
// for loop:
for i in numbers
// fold:
let result2 = numbers.iter .fold;
// they're the same
assert_eq!;
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 = .iter .reduce .unwrap;
assert_eq!;
// Which is equivalent to doing it with `fold`:
let folded = .iter .fold;
assert_eq!;
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 = ;
let iter = a.iter .rev;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
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 = ;
let iter = a.iter;
assert_eq!;
let _ = iter.next;
assert_eq!;
A more complex example:
// The even numbers in the range of zero to nine.
let iter = .iter .filter;
// We might iterate from zero to ten times. Knowing that it's five
// exactly wouldn't be possible without executing filter().
assert_eq!;
// Let's add five more numbers with chain()
let iter = .iter .filter .chain;
// now both bounds are increased by five
assert_eq!;
Returning None
for an upper bound:
// an infinite iterator has no upper bound
// and the maximum possible lower bound
let iter = .iter;
assert_eq!;
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 = ;
let iter = a.iter .skip;
assert_eq!;
assert_eq!;
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 = ;
let iter = a.iter .take;
assert_eq!;
assert_eq!;
assert_eq!;
take()
is often used with an infinite iterator, to make it finite:
let iter = .iter .take;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
If less than n
elements are available, take
will limit itself to the size of the underlying iterator:
let v = ;
let iter = v.iter .take;
assert_eq!;
assert_eq!;
assert_eq!;
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 = ;
assert_eq!;
let a = ;
assert_eq!;
Collect the iterator as a [VecDeque
].
Examples
use VecDeque;
assert_eq!;
Collect the iterator as a [HashSet
].
Examples
use HashSet;
assert_eq!;
Collect the iterator as a [HashMap
].
Examples
use HashMap;
let actual = .iter .map .;
let expected = from;
assert_eq!;
Protocols
Allows iteration to be advanced for the type, this is used for iterators.
for item in value
Allows the value to be converted into an iterator in a for-loop.