Define meaningless temporary variables to solve E0506

#[derive(Debug)]
struct Node {
    prev: Option<Rc<RefCell<Node>>>,
    next: Option<Rc<RefCell<Node>>>,
}

impl Node {
    fn foo(&mut self, x: Rc<RefCell<Node>>) {
        let mut p = Some(x);
        while let Some(ref node) = p {
            p = node.borrow().prev.as_ref()
                .map_or(None, |x| Some(x.clone()));
        }
    }
}

error[E0506]: cannot assign to p because it is borrowed

impl Node {
    fn foo(&mut self, x: Rc<RefCell<Node>>) {
        let mut p = Some(x);
        while let Some(ref node) = p {
            let temp = node.borrow().prev.as_ref()
                .map_or(None, |x| Some(x.clone()));
            p = temp;
        }
    }
}

This works, but the 'temp' variable is pointless, and I feel like the compiler might be able to optimize this

If you use a non-reference pattern for the loop, there's no need for temp:

 impl Node {
     fn foo(&mut self, x: Rc<RefCell<Node>>) {
         let mut p = Some(x);
-        while let Some(ref node) = p {
+        while let Some(node) = p {
             p = node.borrow().prev.as_ref()
                 .map_or(None, |x| Some(x.clone()));
         }
     }
 }
1 Like

Additionally, polonius that is intended for 2023 edition will solve these issues without temporaries.