I encountered a borrowing error

There is a borrowing error in the following code, how should I fix it

use std::{collections::HashMap, rc::Rc};
pub struct Module {
    pub blocks: HashMap<usize, Rc<Block>>,
    pub pc: usize,
    pub history: [History; 1024],
    pub sp: usize,
    pub csp: usize,
}

#[derive(Debug)]
pub struct Block {
    pub results: (usize, i32)
}

#[derive(Debug)]
pub struct History {
    pub block: Rc<Block>,
    pub sp: usize,
}


impl Module {
    fn run(&mut self) {
        let pc = self.pc;
        let block = self.blocks.get(&pc).unwrap();
                 // -------------------- immutable borrow occurs here
        self.push(block.clone(), self.sp);
     // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here

        if block.results.0 > 0 {
        // ----- immutable borrow later used here    
            // todo
        }
    }
    pub(crate) fn push(&mut self, block: Rc<Block>, sp: usize) {

        self.history[self.csp] = History {
            block,
            sp
        };
    }
}

(Playground)

1 Like

block is holding an &Rc<...> that points into the HashMap. You need to clone it to get an independent Rc:

     fn run(&mut self) {
         let pc = self.pc;
-        let block = self.blocks.get(&pc).unwrap();
+        let block = self.blocks.get(&pc).unwrap().clone();
1 Like

yeah, you are so smart, thank you very much

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.