Diff Two Maps Into Added Changed Removed

Compare two HashMaps with get and contains_key to split keys into added, changed and removed buckets, borrowing both maps without cloning values.

RustData Integrity

Code

rustsnippet
56 lines
use std::collections::HashMap;

/// 两张表的差量:新增、变更、删除三类
fn diff(
    old: &HashMap<String, u32>,
    new: &HashMap<String, u32>,
) -> (Vec<String>, Vec<String>, Vec<String>) {
    let mut added = Vec::new();
    let mut changed = Vec::new();
    let mut removed = Vec::new();

    // 只借用两张表:get 返回引用,循环期间不搬移任何值的所有权
    for (key, current) in new {
        match old.get(key) {
            Some(previous) if previous != current => changed.push(key.clone()),
            Some(_) => {}
            None => added.push(key.clone()),
        }
    }
    for key in old.keys() {
        if !new.contains_key(key) {
            removed.push(key.clone());
        }
    }

    // HashMap 顺序不固定:输出前排序保证逐次一致
    added.sort();
    changed.sort();
    removed.sort();
    (added, changed, removed)
}

fn main() {
    let old: HashMap<String, u32> = [
        ("cache", 512),
        ("workers", 4),
        ("timeout", 30),
    ]
    .into_iter()
    .map(|(k, v)| (k.to_string(), v))
    .collect();

    let new: HashMap<String, u32> = [
        ("cache", 1024),
        ("workers", 4),
        ("retries", 3),
    ]
    .into_iter()
    .map(|(k, v)| (k.to_string(), v))
    .collect();

    let (added, changed, removed) = diff(&old, &new);
    println!("added:   {added:?}");
    println!("changed: {changed:?}");
    println!("removed: {removed:?}");
}

Line-by-line reading

Diff Two Maps Into Added Changed Removed reduces to the functions diff and main.

Repetition is confined to for (key, current) in new — the rest of the file is straight-line. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

What to watch for

  • Constructed without dependencies — the registry and lockfile stay untouched.

Applying it

The entry-point signature is fn diff( old: &HashMap<String, u32>, new: &HashMap<String, u32>, ) -> (Vec<String>, Vec<String>, Vec<String>)

The demo output is labeled (added:, changed:, removed:); each label names the call that printed it.

Execute the file and main walks through diff, in that order.

Statements that matter

Some(_) => {}
changed.sort();
removed.sort();

Interactive Tools for This Topic

FAQ

What does Diff Two Maps Into Added Changed Removed print when run?
No setup needed: run the file and look for labeled lines like `added:`, `changed:`, `removed:` in the output.