← All languages
Rust function of the day
Random

HashMap::keys

Return an iterator over the keys of a HashMap.

Description

HashMap::keys returns an iterator visiting all keys in arbitrary order. The iterator element type is &K where K is the key type of the map.

This is useful when you need to inspect or collect all keys without their associated values. The iteration order is not guaranteed and may differ between program runs due to the random hash function.

For iterating over both keys and values, use iter instead.

Example

use std::collections::HashMap;

let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);

let keys: Vec<_> = map.keys().collect();
assert_eq!(keys.len(), 2);

Reference