ora
ora

Reputation: 1

Can't seem to figure out how to avoid using two mutable references when pattern matching in Rust

Below is a bit of code to find the last nested vector in another vector, and returning a mutable reference to it. (Well the code doesn't exactly do that, just a simplified version of my actual code that still produce the error.) As this is part of my first attempt at writing a parser, so I am aware this approach is probably not the best way to handle it. But anyways:

let Content::Block { ref mut body: &mut Vec<Content>, .. } = self.ast.last_mut().unwrap() else {
    return &mut self.ast; // where the error occurs
};
return body;

The compiler complains that return &mut self.ast; is a second mutable borrow, with the first being from self.ast.last_mut().

However after a lot of head scratching and googling I still could not find a way to do this without using two mutable references. My instinct was that there should be a way to drop the first mutable reference created by the time we reached the else branch, but I could not find a way to do that. I tried using mem functions, and then even tried just drop(&mut self.ast) and putting it in a block so the scope ends for it. I have also tried using other ways of pattern matching in hopes that it might be resolved, by using match and if let instead of the let else syntax, and that turned out not to be helpful as well.

My brain is incredible clouded as I am writing this; there might even be a really obvious solution that I am missing. If someone can help me resolve this that'll be great.

Upvotes: 0

Views: 28

Answers (0)

Related Questions