rust - rust : insert uint in hashmap reference

标签 rust reference hashmap borrowing

我是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() 的结果,因为dereferencing (i.e. * ) have a weaker precedence than a method call
因此,它提示取消引用Option<u32>,因为这是 insert() 返回的内容。如果您实际上想取消引用mymap,则必须编写(*mymap).insert("hello world", 0);。但是,Rust中不需要。
如果删除*,则会遇到第二个问题,即您正在尝试对mymap进行变异,这是一个不可变的引用。因此,为了能够在mymap中对f进行突变,您需要向其传递一个可变的引用,即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 - rust : insert uint in hashmap reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65754155/

相关文章:

c++ - 对 `gemmkernel_' 的 undefined reference -- 从 Fortran 调用的 C++ 例程

java - 类在HashMap中使用了非实体[class java.lang.Boolean]?

java - 如何根据这种特殊的 equals 逻辑重写 hashcode 方法

Rust Trait 对象转换

arrays - 有没有办法初始化一个空切片?

testing - 仅在运行测试时生成调试输出

rust - 在 Rust 中使用同一模块中的文件

c++ - 优化行为的差异

c++ - 将复制返回的值分配给引用

java - 如何在xhtml页面中打印Hashmap值