Hi all. I'm just learning rust, and experimenting with the borrow checker with the code below. This code doesn't compile. Somehow, the self.table.insert
operation fails because it is trying to mutably borrow self.table
while the self.table
itself is being immutably borrowed by the self.table.get
in the if
statement. Why does the self.table
is still borrowed when it already in the outside of the if
scope?
Thank you.
use std::collections::HashMap;
struct BP {
table: HashMap<u32, u32>,
}
impl BP {
fn load<'a>(&'a mut self, index: u32) -> &'a u32 {
if let Some(val) = self.table.get(&index) {
return val;
}
let x = 10;
self.table.insert(index, x);
self.table.get(&index).unwrap()
}
}
fn main() {
println!("Hello, world!");
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0502]: cannot borrow `self.table` as mutable because it is also borrowed as immutable
--> src/main.rs:14:9
|
8 | fn load<'a>(&'a mut self, index: u32) -> &'a u32 {
| -- lifetime `'a` defined here
9 | if let Some(val) = self.table.get(&index) {
| ---------------------- immutable borrow occurs here
10 | return val;
| --- returning this value requires that `self.table` is borrowed for `'a`
...
14 | self.table.insert(index, x);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `playground` due to previous error