Hi, I'm trying to work through the Crafting Interpreters tutorial in Rust to help me learn the language and I'm getting stuck when it comes to nesting 'environments'. My code is here:
https://github.com/michaeljones/rox/blob/1dbb2e7e96e37fa696b849e5d9118379e8e1bf38/src/environment.rs
When I compile I get the following errors:
error[E0499]: cannot borrow `*environment` as mutable more than once at a time
--> src/interpreter.rs:25:47
|
23 | pub fn interpret<'a>(&mut self, statements: &Vec<Stmt>, environment: &'a mut Environment<'a>) {
| -- lifetime `'a` defined here
24 | for statement in statements {
25 | self.execute_statement(statement, environment);
| ----------------------------------^^^^^^^^^^^-
| | |
| | mutable borrow starts here in previous iteration of loop
| argument requires that `*environment` is borrowed for `'a`
error[E0597]: `block_environment` does not live long enough
--> src/interpreter.rs:33:48
|
29 | fn execute_statement<'a>(&mut self, statement: &Stmt, environment: &'a mut Environment<'a>) {
| -- lifetime `'a` defined here
...
33 | self.execute_block(statements, &mut block_environment);
| -------------------------------^^^^^^^^^^^^^^^^^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `block_environment` is borrowed for `'a`
34 | }
| - `block_environment` dropped here while still borrowed
error[E0499]: cannot borrow `*environment` as mutable more than once at a time
--> src/interpreter.rs:64:47
|
62 | fn execute_block<'a>(&mut self, statements: &Vec<Stmt>, environment: &'a mut Environment<'a>) {
| -- lifetime `'a` defined here
63 | for statement in statements {
64 | self.execute_statement(statement, environment);
| ----------------------------------^^^^^^^^^^^-
| | |
| | mutable borrow starts here in previous iteration of loop
| argument requires that `*environment` is borrowed for `'a`
error: aborting due to 3 previous errors
I've tried googling around but I'm stuck. It feels like the compiler is wanting to borrow enviroment
for longer than I want it to when passing it into execute_statement
but I can sort of see from the lifetime annotations why that might happen but I don't know how to make it borrow it for less time (just one iteration of the loop.)
I thought maybe trying to create a new reference? Or googling how to make a new lifetime that is shorter or something?
I imagine I might have to restructure things but I've no idea how. I'm already straying from the path the author takes in the book as he is using Java and just juggles some references around.
Clearly I'm new to this and flailing around. I'm sorry that I've just linked to a whole repository but I think the issues are isolated to the two files and often it is best to see the actual code that is wrong rather than my attempt to simplify it.
Any help would be much appreciated.