我想做以下事情:
Vec
某个键,并将其存储起来供以后使用.Vec
则为该键创建一个空,但仍将其保留在变量中.如何有效地做到这一点?当然我以为我可以使用match
:
use std::collections::HashMap;
// This code doesn't compile.
let mut map = HashMap::new();
let key = "foo";
let values: &Vec<isize> = match map.get(key) {
Some(v) => v,
None => {
let default: Vec<isize> = Vec::new();
map.insert(key, default);
&default
}
};
Run Code Online (Sandbox Code Playgroud)
当我尝试它时,它给了我错误,如:
error[E0502]: cannot borrow `map` as mutable because it is also borrowed as immutable
--> src/main.rs:11:13
|
7 | let values: &Vec<isize> = match map.get(key) {
| --- immutable borrow occurs …
Run Code Online (Sandbox Code Playgroud)