Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Rust Dictionary

  1. Home
  2. Rust Dictionary
  3. HashMap::keys() / values() / iter()

HashMap::keys() / values() / iter()

Since: Rust 1.0(2015)

Methods for iterating over the keys, values, or key-value pairs of a HashMap. Use these methods when you need to process the contents of a map in a loop.

Syntax

for key in map.keys() { }

// Generate an iterator over value references.
for value in map.values() { }

// Generate an iterator over key-value pairs (tuples).
for (key, value) in map.iter() { }

// Generate an iterator that takes ownership of keys and values (consumes the map).
for (key, value) in map.into_iter() { }

Method Reference

MethodDescription
keys()Returns an iterator over key references. Use when you only need to process keys.
values()Returns an iterator over value references. Use when you only need to process values.
values_mut()Returns an iterator over mutable value references. Use when you need to modify values in the loop.
iter()Returns an iterator over (&K, &V) pairs. The most common general-purpose iteration method.
iter_mut()Returns an iterator over (&K, &mut V) pairs.
into_iter()Returns an iterator over (K, V) pairs with ownership. The map cannot be used after this call.

Sample Code

sample_hashmap_keys_values_iter.rs
use std::collections::HashMap;

fn main() {
    let mut scores: HashMap<String, i32> = HashMap::new();
    scores.insert(String::from("user_a"), 100);
    scores.insert(String::from("user_c"), 85);
    scores.insert(String::from("user_e"), 92);

    // Iterate over keys only.
    println!("--- keys ---");
    for key in scores.keys() {
        println!("{}", key);
    }

    // Iterate over values only.
    println!("--- values ---");
    for val in scores.values() {
        println!("{}", val);
    }

    // Iterate over key-value pairs.
    println!("--- iter ---");
    for (name, score) in scores.iter() {
        println!("{}: {}", name, score);
    }

    // Use values_mut() to modify values in the loop.
    for val in scores.values_mut() {
        *val += 5; // Add 5 points to everyone's score.
    }
    println!("after +5: {:?}", scores);
}

Compile with the following command:

rustc hashmap_keys_values_iter.rs
./hashmap_keys_values_iter
--- keys ---
user_a
user_c
user_e
--- values ---
100
85
92
--- iter ---
user_a: 100
user_c: 85
user_e: 92
after +5: {"user_a": 105, "user_c": 90, "user_e": 97}

Common Mistakes

Common mistake 1: using the map after calling into_iter()

into_iter() consumes the map. The variable is no longer usable after calling it.

use std::collections::HashMap;

fn main() {
    let mut scores: HashMap<String, i32> = HashMap::new();
    scores.insert("user_a".to_string(), 100);

    for (name, score) in scores.into_iter() {
        println!("{}: {}", name, score);
    }

    // Compile error: `scores` has been moved
    // println!("{:?}", scores);
}

The same logic can also be written as:

use std::collections::HashMap;

fn main() {
    let mut scores: HashMap<String, i32> = HashMap::new();
    scores.insert("user_a".to_string(), 100);

    // Use iter() to keep the map available after the loop
    for (name, score) in scores.iter() {
        println!("{}: {}", name, score);
    }
    println!("count: {}", scores.len()); // still accessible
}

Common mistake 2: modifying the map during iteration

Adding or removing entries while iterating is a compile error due to Rust's borrow rules. Collect the keys to remove first, then perform the removals afterward.

use std::collections::HashMap;

fn main() {
    let mut scores: HashMap<String, i32> = HashMap::new();
    scores.insert("user_c".to_string(), 90);
    scores.insert("user_a".to_string(), 80);

    // Use retain() to remove entries based on a condition
    scores.retain(|_, score| *score >= 85);
    println!("{:?}", scores);
}

Overview

Choose the right iteration method based on your needs: keys() when you only need keys, values() when you only need values, and iter() when you need both. The order of iteration in a HashMap depends on the hash values, not the insertion order, so it may differ between runs.

Use values_mut() or iter_mut() when you need to modify values inside the loop. If the map itself is no longer needed after the loop, into_iter() is more efficient as it takes ownership. Note that the map cannot be used after calling into_iter().

If you find any errors or copyright issues, please .