我想做类似这段代码的事情:
use std::collections::HashMap;
fn main() {
let mut vars = HashMap::<String, String>::new();
find_and_do_someth(&mut vars);
}
fn find_and_do_someth(map: &mut HashMap<String, String>) {
match map.get("test") {
None => { /* Do nothing */ }
Some(string) => do_someth(map, string),
}
}
fn do_someth(map: &mut HashMap<String, String>, val: &str) {
// Do something that alters map
}
我收到以下编译错误:
error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable
--> src/main.rs:11:35
|
9 | match map.get("test") {
| --- immutable borrow occurs here
10 | None => { /* Do nothing */ }
11 | Some(string) => do_someth(map, string),
| ^^^ mutable borrow occurs here
12 | }
| - immutable borrow ends here
这个用例是否存在一般的Rust友好解决方案?
以上只是使用HashMap
的简单示例。
逐个案例,我似乎总能找到一个复杂的解决方案,但是我还没有用到掌握Rust的必要思路。