Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Iterate over key-value pairs in a Hash

  • keys

  • iter

  • Use the iter method to get the iterator

  • Though you can iterate over the hash directly. It does the same.

use std::collections::HashMap;

fn main() {
    let counter = HashMap::from([("foo", 1), ("bar", 2)]);
    println!("{:?}", counter);
    println!("{:?}", counter.keys());

    for (name, value) in counter.iter() {
        println!("{} : {}", name, value);
    }
    println!();

    for (name, value) in counter {
        println!("{} : {}", name, value);
    }
}
{"bar": 2, "foo": 1}
["bar", "foo"]
bar : 2
foo : 1

bar : 2
foo : 1