Hello, I am new to rust. After fighting the borrow checker for a little while, I decided to get some help. Here is my main
function:
fn main() {
let my_fiz = Fiz {x: 0, y: 1};
let mut my_foo = Foo::new();
my_foo.foobar1(0, String::from("foobar"));
my_foo.foobar2(0);
}
and here are the associated structs:
#[derive(Debug, Default)]
struct Foo<'a> {
x: HashMap<String, Bar<'a>>,
y: HashMap<u32, Fiz>,
}
#[derive(Debug, Default)]
struct Bar<'a> {
x: u32,
y: HashMap<&'a Fiz, String>,
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct Fiz {
x: i32,
y: i32,
}
impl<'a> Foo<'a> {
pub fn new() -> Foo<'a> {
let mut abc = Foo::default();
abc.y.insert(0, Fiz {x: 10, y: 10});
abc.x.insert(String::from("foobar"), Bar { x: 0, y: HashMap::new() });
abc
}
pub fn foobar1(&'a mut self, x: u32, y: String) -> Entry<'_, &'a Fiz, String> {
let a = self.y.get(&x).unwrap();
let b = self.x.entry(y).or_insert_with(Bar::default);
b.y.entry(a)
}
pub fn foobar2(&mut self, x: u32) {
// do something here...
}
}
You can find the entire code on the playground. The problem with the code is that it raises this error:
error[E0499]: cannot borrow `my_foo` as mutable more than once at a time
--> src/main.rs:45:5
|
44 | my_foo.foobar1(0, String::from("foobar"));
| ------ first mutable borrow occurs here
45 | my_foo.foobar2(0);
| ^^^^^^
| |
| second mutable borrow occurs here
| first borrow later used here
I know that I can't use mutable references multiple times, so how do I get around this? Thanks!