Rust:在 hashmap 引用中插入 uint

Rust : insert uint in hashmap reference

我是 Rust 的新手,我在编译时遇到这个错误,但我不明白

error[E0614]: type `Option<u32>` cannot be dereferenced
 --> src/main.rs:9:5
  |
9 |     *mymap.insert("hello world", 0);
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

这是我为重现问题而简化的代码:

use std::collections::HashMap;

fn main() {
    let mymap: HashMap<&str, u32> = HashMap::new();
    f(&mymap)
}

fn f(mymap: &HashMap<&str, u32>) {
    *mymap.insert("hello world", 0);
}

同样下面的也不行

*mymap.insert("hello world", &0);

我没有通过谷歌搜索找到我的问题的根本原因,我想我没有词。看起来像是一些借用问题。

您实际上并没有取消引用 mymap,您实际上是在取消引用 insert(), because dereferencing (i.e. *) have a weaker precedence than a method call 的结果。

所以它抱怨取消引用 Option<u32> 因为那是 insert() returns。如果你真的想取消引用 mymap 你必须写 (*mymap).insert("hello world", 0);。但是,在 Rust 中不需要这样做。

如果删除 *,则会遇到第二个问题,即您正试图改变 mymap,这是一个不可变的引用。因此,为了能够插入,即在 f 中改变 mymap,您需要向其传递一个可变引用,即 mymap: &mut HashMap<&str, u32>.

use std::collections::HashMap;

fn main() {
    let mut mymap: HashMap<&str, u32> = HashMap::new();
    f(&mut mymap)
}

fn f(mymap: &mut HashMap<&str, u32>) {
    mymap.insert("hello world", 0);
}

您不需要取消对方法调用的引用,Rust 会自动为您完成。此外,您需要传递 mymap 的可变引用,以便您可以实际执行 insert。固定示例:

use std::collections::HashMap;

fn main() {
    let mut mymap: HashMap<&str, u32> = HashMap::new();
    f(&mut mymap)
}

fn f(mymap: &mut HashMap<&str, u32>) {
    mymap.insert("hello world", 0);
}

playground