Struct std::collections::hash_map::Keys

Overview

An iterator over a the keys in a hash map.

Trait Implementations

impl Iterator for Keys
fn next(value: any) -> 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());
fn nth(value: any, value1: u64) -> Option

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.iter().nth(1), Some(2));

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

let a = [1, 2, 3];

let iter = a.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.iter().nth(10), None);
fn size_hint(value: any)

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!(iter.size_hint(), (3u64, Some(3)));
let _ = iter.next();
assert_eq!(iter.size_hint(), (2u64, Some(2)));

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!(iter.size_hint(), (0, Some(10)));

// 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!(iter.size_hint(), (5, Some(15)));

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!(iter.size_hint(), (u64::MAX, None));
fn count(value: any) -> u64

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 fold(value: any, value1: any, value2: Function) -> any

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(value: any, value1: 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 find(value: any, value1: 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(value: any, value1: 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(value: any, value1: 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(value: any, value1: any) -> Chain

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 enumerate(value: any) -> Enumerate

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((0u64, 'a')));
assert_eq!(iter.next(), Some((1u64, 'b')));
assert_eq!(iter.next(), Some((2u64, 'c')));
assert_eq!(iter.next(), None);
fn filter(value: any, value1: Function) -> Filter

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(value: any, value1: Function) -> Map

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);
}
fn filter_map(value: any, value1: Function) -> FilterMap

Creates an iterator that both filters and maps.

The returned iterator yields only the values for which the supplied closure returns Some(value).

filter_map can be used to make chains of filter and map more concise. The example below shows how a map().filter().map() can be shortened to a single call to filter_map.

Examples

Basic usage:

let a = ["1", "two", "NaN", "four", "5"];

let iter = a.iter().filter_map(|s| s.parse::<i64>().ok());

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

Here's the same example, but with filter and map:

let a = ["1", "two", "NaN", "four", "5"];
let iter = a.iter().map(|s| s.parse::<i64>()).filter(|s| s.is_ok()).map(|s| s.unwrap());
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(5));
assert_eq!(iter.next(), None);
fn flat_map(value: any, value1: Function) -> FlatMap

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");
fn peekable(value: any) -> Peekable

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 skip(value: any, value1: u64) -> Skip

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(value: any, value1: u64) -> Take

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 sum<u64>(value: any) -> u64

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 i64, float and u64. 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 = [1u64, 2u64, 3u64];
let sum = a.iter().sum::<u64>();

assert_eq!(sum, 6u64);
fn sum<i64>(value: any) -> 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 i64, float and u64. 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<f64>(value: any) -> 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 i64, float and u64. 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 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]);
fn collect<VecDeque>(self, ..) -> VecDeque

Collect the iterator as a [VecDeque].

Examples

use std::collections::VecDeque;

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

Collect the iterator as a [HashSet].

Examples

use std::collections::HashSet;

let a = (0..3).iter().collect::<HashSet>();
let b = HashSet::from_iter([0, 1, 2]);

assert_eq!(a, b);
fn collect<HashMap>(self, ..) -> HashMap

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_iter([
   (0, "0"),
   (1, "1"),
   (2, "2"),
]);

assert_eq!(actual, expected);
fn collect<Object>(self, ..) -> HashMap

Collect the iterator as an [Object].

Examples

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

Collect the iterator as a [Tuple].

Examples

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

Collect the iterator as a [String].

Examples

assert_eq!(["first", "second"].iter().collect::<String>(), "firstsecond");
fn product<u64>(value: any) -> u64

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 i64, f64 and u64. 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) {
   (1u64..=n).iter().product::<u64>()
}

assert_eq!(factorial(0u64), 1u64);
assert_eq!(factorial(1u64), 1u64);
assert_eq!(factorial(5u64), 120u64);
fn product<i64>(value: any) -> 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 i64, f64 and u64. 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<f64>(value: any) -> 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 i64, f64 and u64. 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);

Protocols

protocol NEXT
let $out = value.next()

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

protocol SIZE_HINT
let $out = value.size_hint()

Get the size hint of an iterator.

protocol NTH
let $out = value.nth(index)

Allows iteration to be advanced for the type to the nth element, 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.