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

Merge HashMaps (extend)

  • extend

  • If the same key appears twice, the value of the second one wins.

use std::collections::HashMap;
fn main() {
    let a = HashMap::from([("apple", 1), ("banana", 1)]);
    let b = HashMap::from([("apple", 2), ("peach", 2), ("grape", 2)]);

    let mut total: HashMap<&str, i32> = HashMap::new();
    total.extend(a);
    println!("{:#?}", total);

    total.extend(b);
    println!("{:#?}", total);
}
{
    "apple": 1,
    "banana": 1,
}
{
    "peach": 2,
    "banana": 1,
    "grape": 2,
    "apple": 2,
}