I'm new to Rust, and I'm struggling with the following question for which I cannot find simple answer.
Defining a struct with a HashMap
field, I can't modify this HashMap in a mutable method:
use std::collections::HashMap;
struct ASet {
myset: HashMap<String,u8>,
}
impl ASet {
fn new() -> ASet {
ASet {
myset: HashMap::new(),
}
}
fn fill(&mut self){
self.myset.insert("John".to_string(), 12);
}
fn modify_all(&mut self){
for (name, age) in &self.myset{
println!("Removing {} who is {}", name, age);
self.myset.remove(name);
}
}
}
fn main() {
let mut my_struct_set = ASet::new();
my_struct_set.fill();
my_struct_set.modify_all();
}
Here is the error:
Compiling playground v0.0.1 (/playground)
error[E0502]: cannot borrow `self.myset` as mutable because it is also borrowed as immutable
--> src/main.rs:23:13
|
21 | for (name, age) in &self.myset{
| -----------
| |
| immutable borrow occurs here
| immutable borrow later used here
22 | println!("Removing {} who is {}", name, age);
23 | self.myset.remove(name);
| ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0502`.
error: could not compile `playground`
(Can be tested here)
Edit: the answer is here: Why do immutable borrow and usage occur at the same place?