BTreeMap Append Merges Maps

Merge two BTreeMap values with append, watch duplicate keys take the incoming value, and confirm the source map becomes empty.

RustData Integrity

Code

rustsnippet
22 lines
use std::collections::BTreeMap;

fn main() {
    let mut current: BTreeMap<&str, u32> = BTreeMap::new();
    current.insert("build", 3);
    current.insert("test", 5);
    current.insert("lint", 1);

    let mut incoming: BTreeMap<&str, u32> = BTreeMap::new();
    incoming.insert("test", 9);
    incoming.insert("deploy", 2);

    // append merges every entry and overwrites duplicate keys
    current.append(&mut incoming);
    println!("current: {current:?}");
    println!("incoming empty: {}", incoming.is_empty());
    println!("test value: {}", current["test"]);

    // the moved map no longer owns any entries
    println!("incoming len: {}", incoming.len());
    println!("keys: {:?}", current.keys().collect::<Vec<_>>());
}

What the code does

Under the hood: the function main.

Caveats

  • Copy, run: the standard library answers every call in the file.

Applying it

The primary signature is fn main()

Each run prints the 3 labeled blocks current:, incoming empty:, test value: in source order.

Statements that matter

let mut incoming: BTreeMap<&str, u32> = BTreeMap::new();
let mut current: BTreeMap<&str, u32> = BTreeMap::new();
current.append(&mut incoming);

Interactive Tools for This Topic

FAQ

What does BTreeMap Append Merges Maps print when run?
Running the file directly is enough — expect labeled output lines such as `current:`, `incoming empty:`, `test value:`.