I was trying to make a Disjoint-Set data structure in Rust. The relevant code is:
pub struct Set<'a, T: 'a> {
rank: u32,
value: T,
parent: Option<&'a mut Set<'a, T>>,
}
impl<'a, T> Set<'a, T> {
pub fn find(&'a mut self) -> &'a mut Set<'a, T> {
match self.parent {
None => self,
Some(mut p) => {
self.parent = Some(p.find());
self.parent.unwrap()
}
}
}
}
The errors I get are:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:9:15
|
9 | match self.parent {
| ^^^^ cannot move out of borrowed content
10 | None => self,
11 | Some(mut p) => {
| ----- hint: to prevent move, use `ref p` or `ref mut p`
error[E0507]: cannot move out of borrowed content
--> src/main.rs:13:17
|
13 | self.parent.unwrap()
| ^^^^ cannot move out of borrowed content
I'm not sure I understand the borrow checker fully, but I am using references to avoid taking ownership of structs themselves so that they can be pointed to and reassigned similar to how you would in other languages.
I can avoid these errors by removing the mut
from the references in the struct, but then I cannot change the parent of each set because they are immutable.
I have read through similar questions such as:
- Rust: "cannot move out of `self` because it is borrowed" error
- Can't borrow File from &mut self (error msg: cannot move out of borrowed content)
These aren't helping me work out how to solve this issue. I have also tried restructuring the function find
as well as the struct itself to use Rc<RefCell<Set>>
and Box<Set>
but I always end up at the same error.
What is this error and how do I fix it?
unwrap
consumes theOption
. – Shepmasteras_mut()
on the second error makes it so that I am returning a mutable reference to a mutable reference to the struct which didn't seem to work either. Even trying to spread this function out to take each part in step didn't seem to fix it. – mcdonalda1993