我有以下代码将一些值插入HashMap,然后将它们取回:
use std::collections::HashMap;
fn things() {
let mut map = HashMap::new();
map.insert(5, "thing");
map.insert(4, "world");
map.insert(1, "hello");
let mut thing = map.remove(&5);
let mut world = map.get_mut(&4);
let mut hello = map.get_mut(&1);
}
Run Code Online (Sandbox Code Playgroud)
尝试编译此代码会出现以下错误:
error[E0499]: cannot borrow `map` as mutable more than once at a time
--> src/main.rs:10:21
|
9 | let mut world = map.get_mut(&4);
| --- first mutable borrow occurs here
10 | let mut hello = map.get_mut(&1);
| ^^^ second mutable borrow occurs here
11 | } …Run Code Online (Sandbox Code Playgroud) 我有一个HashMap,它使用a char作为键,使用a 作为struct值.
HashMap的get()方法通常会使用不在HashMap中的键来调用,因此我想unwrap_or()在返回的Option上使用它来创建默认struct值.但是,当我尝试这样做时,编译器抛出以下错误(temp作为我试图返回的默认值):
lib.rs:51:4: 51:8 error: `temp` does not live long enough
Run Code Online (Sandbox Code Playgroud)
这是一个小型的复制品:
struct Sample {
thing: i32
}
fn do_stuff() {
let map = HashMap::<char, Sample>::new();
let sample = map.get(&'a').unwrap_or({
let temp = Sample {
thing : 0
};
&temp
});
}
Run Code Online (Sandbox Code Playgroud)
我有两个问题:
temp绑定活得更久?struct使用选项时是否有更好的方法可以回退到默认值?