[英]Rust : insert uint in hashmap reference
I am new to Rust and I have this error at compilation time but I don't get it我是 Rust 的新手,在编译时出现此错误,但我不明白
error[E0614]: type `Option<u32>` cannot be dereferenced
--> src/main.rs:9:5
|
9 | *mymap.insert("hello world", 0);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Here is my code simplified to reproduce the issue:这是我的简化代码以重现该问题:
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);
}
Also the following does not work either以下也不起作用
*mymap.insert("hello world", &0);
I don't find the root cause of my problem by googling it, I think I don't have the words.我没有通过谷歌搜索找到问题的根本原因,我想我没有的话。 It looks like some borrowing issue.好像是借款的问题。
You're actually not dereferencing mymap
, you're actually dereferencing the result of insert()
, because dereferencing (ie *
) have a weaker precedence than a method call .您实际上并没有取消引用mymap
,而是取消了insert()
的结果,因为取消引用(即*
)的优先级低于方法调用。
So it complains about dereferencing an Option<u32>
because that's what insert()
returns.所以它抱怨取消引用Option<u32>
因为那是insert()
返回的内容。 If you actually wanted to dereference mymap
you'd have to write (*mymap).insert("hello world", 0);
如果你真的想取消引用mymap
你必须写(*mymap).insert("hello world", 0);
. . However, that is not needed in Rust.但是,在 Rust 中不需要。
If you remove the *
then you will get a second problem, which is that you're attempting to mutate mymap
, which is an immutable reference.如果你删除*
那么你会遇到第二个问题,那就是你试图改变mymap
,这是一个不可变的引用。 So to be able to insert, ie mutate mymap
in f
, you need to pass it a mutable reference, ie mymap: &mut HashMap<&str, u32>
.因此,为了能够插入,即在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);
}
You don't need to dereference references on method calls, Rust will automatically do that for you.您不需要取消对方法调用的引用,Rust 会自动为您执行此操作。 Also, you need to pass a mutable reference of mymap
so you can actually perform the insert
.此外,您需要传递mymap
的可变引用,以便您可以实际执行insert
。 Fixed example:固定示例:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.