0PricingLogin
Learn Rust Coding · Lesson

HashMaps

Key-value storage.

What Is a HashMap?

A HashMap<K, V> stores key-value pairs. You look up values by their key instead of by position.

You must import it from the standard library.

use std::collections::HashMap;

fn main() {
    let map: HashMap<String, i32> = HashMap::new();
    println!("{} entries", map.len());
}

Importing HashMap

HashMap is not in the prelude, so add this line at the top of your file:

  • use std::collections::HashMap;
use std::collections::HashMap;

fn main() {
    let scores: HashMap<&str, i32> = HashMap::new();
    println!("empty: {}", scores.is_empty());
}

All lessons in this course

  1. Vectors
  2. Strings and &str
  3. HashMaps
  4. Iterating Collections
← Back to Learn Rust Coding