Hello, I am a beginner trying to learn Rust by building a simple interpreted programming language. While programming blocks for the language, I ran into this lifetime error which I have trouble understanding.
So here is the code for the Block struct:
#[derive(Debug)]
pub struct Block<'a> {
pub stmts: Vec<Stmt>,
//The list of variables in the scope of the current block
pub vars: HashMap<String, Literal>,
pub parent: Option<Box<&'a mut Block<'a>>>,
}
impl<'a> Block<'a> {
pub fn new(stmts: Vec<Stmt>, parent: Option<&'a mut Block<'a>>) -> Self {
let parent = parent.map(Box::new);
Self {
stmts,
vars: HashMap::new(),
parent,
}
}
pub fn execute(&mut self, print_expr_result: bool) {
//execute all statements in the block
let stmts = self.stmts.clone();
for stmt in stmts.iter() {
self.execute_stmt(stmt, print_expr_result);
}
}
fn execute_stmt(&mut self, stmt: &Stmt, print_expr_result: bool) {
//Execute a single statement
match stmt {
//Other statements match, some of them require &mut self
//...
Stmt::Block(stmts) => {
let mut block = Block::new(stmts.clone(), Some(self));
block.execute(print_expr_result);
}
}
}
//Other methods
//...
}
Trying to compile this code gives the following error:
I am struggling to understand why the &mut self
doesn't outlive the block's lifetime. Wouldn't the block go out of scope before the reference?
fn execute_stmt(&mut self, stmt: &Stmt, print_expr_result: bool) {
match stmt {
//...
Stmt::Block(stmts) => {
let mut block = Block::new(stmts.clone(), Some(self)); //<---- Block created here
block.execute(print_expr_result);
} //<---- Block goes out of scope here
}
}//<---- &mut self goes out of scope here
At this point I am almost certain I need to use RefCell or Rc to fix this, but any help in understanding why this causes an error would be appreciated!