Consume Maps With into_keys And into_values

Break a HashMap apart by ownership: into_keys hands each key to the consumer, into_values does the same for values, without cloning anything.

RustData Integrity

Code

rustsnippet
31 lines
use std::collections::{BTreeSet, HashMap};

fn main() {
    // a request-count table: taken apart by ownership once processing finishes
    let mut counts: HashMap<String, u64> = HashMap::new();
    for route in ["GET /health", "POST /orders", "GET /health", "GET /users"] {
        *counts.entry(route.to_string()).or_insert(0) += 1;
    }

    // into_keys consumes the map: ownership of the keys moves wholesale, collected into a sorted set
    let routes: BTreeSet<String> = counts.into_keys().collect();
    println!("routes (sorted):");
    for route in &routes {
        println!("  {route}");
    }

    // rebuilding the map shows into_values: ownership of the values moves, summed directly
    let mut counts: HashMap<String, u64> = HashMap::new();
    counts.insert("a".to_string(), 3);
    counts.insert("b".to_string(), 5);
    let total: u64 = counts.into_values().sum();
    println!("total: {total}");

    // the same works when values are complex types: into_values hands over owned elements
    let mut tags: HashMap<&str, Vec<&str>> = HashMap::new();
    tags.insert("rust", vec!["systems", "compiled"]);
    tags.insert("go", vec!["concurrent"]);
    let mut all: Vec<&str> = tags.into_values().flatten().collect();
    all.sort_unstable(); // HashMap has no order: sorting before display keeps output stable
    println!("all tags: {all:?}");
}

What the code does

Consume Maps With into_keys And into_values comes down to the function main.

Iteration happens inside for route in ["GET /health", "POST /orders", "GET /health", "GET /users"] — everything outside it runs once.

Applying it

Look for the routes (sorted):, total:, all tags: prefixes when the file runs; they tie each line to its step.

Statements that matter

let mut all: Vec<&str> = tags.into_values().flatten().collect();
let routes: BTreeSet<String> = counts.into_keys().collect();
let total: u64 = counts.into_values().sum();

Interactive Tools for This Topic

FAQ

What does Consume Maps With into_keys And into_values print when run?
No setup needed: run the file and look for labeled lines like `routes (sorted):`, `total:`, `all tags:` in the output.