我是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/