I have a datatype that is recursive. I want to expose a mutable reference to the last deepest value of the structure, and I have this code to do this:
pub fn get_last_deepest_mut(&mut self) -> Option<&mut Self> {
let mut instruction_ref: &mut Instruction = self;
while let Some(inner_loop_block) = instruction_ref.get_inner_mut() {
instruction_ref = inner_loop_block.last_mut()?;
}
Some(instruction_ref)
}
However, although I am 90% sure that this code is safe and sound, the compiler throws an error at me:
error[E0499]: cannot borrow `*instruction_ref` as mutable more than once at a time
--> src/lib/instruction.rs:63:8
|
56 | pub fn get_last_deepest_mut(&mut self) -> Option<&mut Self> {
| - let's call the lifetime of this reference `'1`
...
59 | while let Some(inner_loop_block) = instruction_ref.get_inner_mut() {
| --------------- first mutable borrow occurs here
...
63 | Some(instruction_ref)
| -----^^^^^^^^^^^^^^^-
| | |
| | second mutable borrow occurs here
| returning this value requires that `*instruction_ref` is borrowed for `'1`
This error is incredibly confusing, and I was not able to resolve it without using raw pointers. Is it possible to resolve this error without resorting to pointers?