I want to do something similar to this code:
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
}
I get the following compiler error:
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
Is there a general Rust-friendly work-around for this use case?
- Check something on an object
- If condition is verified, alter the object
The above is just a simple example using a HashMap
.
Case by case, I seem to always find a convoluted solution, however I am not used yet to the way of thinking necessary to master Rust.