Here is a tiny reproducible replica of my code.
use std::collections::{HashMap};
struct Foobar {
foo: HashMap<char, i32>,
bar: Vec<i32>,
}
impl Foobar {
fn new() -> Self {
Self {
foo: HashMap::new(),
bar: Vec::new(),
}
}
fn get_item_from_foo(&mut self, t: char) -> &mut i32 {
self.foo.entry(t).or_insert(0)
}
fn push_to_bar(&mut self, t: char) {
let borrow = self.get_item_from_foo(t);
self.bar.push(0);
*borrow = 0;
}
}
You can also see the code here at the playground.
Let me explain: in the function push_to_bar
I firstly borrow an item form self.foo
, then append an element to self.bar
, at last I need to modify the borrowed item. This seems correct. But the compiler gives me an error.
error[E0499]: cannot borrow `self.bar` as mutable more than once at a time
--> src/main.rs:22:9
|
21 | let borrow = self.get_item_from_foo(t);
| ---- first mutable borrow occurs here
22 | self.bar.push(0);
| ^^^^^^^^ second mutable borrow occurs here
23 | *borrow = 0;
| ----------- first borrow later used here
error: aborting due to previous error
In my comprehension, the function get_item_from_foo
doesn't borrow the entire self
. And there is no shared memory between foo
and bar
. What's the wrong with my code? I'm glad if anyone can help.