如何将 HashMap 传递给 Rust 中的函数

chr*_*h-k 4 hashmap rust

谁能解释为什么下面的代码不能编译?

use std::collections::HashMap;

fn add(mut h: &HashMap<&str, &str>) {
    h.insert("foo", "bar");
}

fn main() {
    let mut h: HashMap<&str, &str> = HashMap::new();
    add(&h);
    println!("{:?}", h.get("foo"));
}
Run Code Online (Sandbox Code Playgroud)

这就是 rustc 告诉我的

hashtest.rs:4:5: 4:6 error: cannot borrow immutable borrowed content `*h` as mutable
hashtest.rs:4     h.insert("foo", "bar");
                  ^
Run Code Online (Sandbox Code Playgroud)

Val*_*ntz 14

问题是您传递了对 HashMap的可变引用(即引用可以更改为指向另一个HashMap),而不是对可变引用 HashMap(即HashMap可以更改)。

这是一个正确的代码:

use std::collections::HashMap;

fn add(h: &mut HashMap<&str, &str>) {
    h.insert("foo", "bar");
}

fn main() {
    let mut h: HashMap<&str, &str> = HashMap::new();
    add(&mut h);
    println!("{:?}", h.get("foo"));
}
Run Code Online (Sandbox Code Playgroud)