I am going through the "fighting the borrow checker phase" of learning Rust. I have this code:
use std::collections::HashMap;
#[derive(Default)]
struct Foo<'a> {
str_bar: HashMap<String, Bar<'a>>,
}
struct Bar<'a> {
x: u32,
y: Vec<&'a Fiz>,
}
struct Fiz {
x: i32,
y: i32,
}
impl<'a> Foo<'a> {
pub fn new() -> Foo<'a> {
Foo::default()
}
pub fn add_str_bar(&mut self, string: String, fiz: &'a Fiz) {
self.str_bar.insert(string, Bar { x: 0, y: vec![fiz] });
}
pub fn read_str_bar(&mut self, string: String, fiz: &'a mut Fiz) {
// do something...
}
}
fn main() {
let mut my_foo = Foo::new();
let mut my_bar = Fiz { x: 0, y: 1 };
// I can't change the order of this
my_foo.add_str_bar(String::from("foobar"), &my_bar);
my_foo.read_str_bar(String::from("fizbar"), &mut my_bar);
println!("hello world");
}
This does not compile:
error[E0502]: cannot borrow `my_bar` as mutable because it is also borrowed as immutable
--> src/main.rs:38:49
|
37 | my_foo.add_str_bar(String::from("foobar"), &my_bar);
| ------- immutable borrow occurs here
38 | my_foo.read_str_bar(String::from("fizbar"), &mut my_bar);
| ------------ ^^^^^^^^^^^ mutable borrow occurs here
| |
| immutable borrow later used by call
How do I get around this without changing the order of the statements?