Borrow Two Map Entries With get_many_mut

Take disjoint mutable borrows of two HashMap entries in one call with get_many_mut, so transfers can hold both sides at once.

RustData Integrity

Code

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

fn main() {
    let mut balances: HashMap<String, i64> = HashMap::from([
        ("alice".to_string(), 100),
        ("bob".to_string(), 30),
    ]);

    // 一次调用借到两个不相交键的可变引用:转账必须同时持有双方
    let [alice, bob] = balances
        .get_many_mut(["alice", "bob"])
        .expect("both keys exist");
    *alice -= 40;
    *bob += 40;

    println!("alice: {}", balances["alice"]);
    println!("bob: {}", balances["bob"]);

    // 任一键缺失,整组返回 None,不会给出部分借用
    let missing = balances.get_many_mut(["alice", "ghost"]);
    assert!(missing.is_none());
    println!("missing key: whole group is None");
}

How it works

Borrow Two Map Entries With get_many_mut reduces to the function main.

What to watch for

  • The package manager never enters the picture for this snippet.

Putting it to use

The main signature reads fn main()

Expect labeled output — alice:, bob:, missing key: whole group is None — when the file runs.

Core lines

let missing = balances.get_many_mut(["alice", "ghost"]);
.get_many_mut(["alice", "bob"])
.expect("both keys exist");
assert!(missing.is_none());

Interactive Tools for This Topic

FAQ

What does Borrow Two Map Entries With get_many_mut print when run?
No setup needed: run the file and look for labeled lines like `alice:`, `bob:`, `missing key: whole group is None` in the output.