Hey everyone!
I have been tasked with constructing a program that uses a glorified binary tree. It has a struct that looks like this,
left: Option<Box<Light>>,
right: Option<Box<Light>>,
brightness: i32,
}
I need to implement a way to read in instructions (which is complete), which include the following,
enum Instruction {
Set(i32),
Left,
Right,
Reset,
}```
To summarise, Set will set the "brightness" of the current node. Left will go down the tree to the left, Right will go down to the right, Reset will go back to the top of the tree.
This is my current main function.
```fn main() {
let instructions = get_instructions_from_stdin();
let mut light = Box::new(Light { left: None, right: None, brightness: 0});
let mut curr = &mut light;
for instruction in &instructions{
match instruction {
Instruction::Set(x) => curr.brightness = *x,
Instruction::Left => match &mut curr.left {
Some( next) => curr = next,
None => {
let mut newLight = Box::new(Light { left: None, right: None, brightness: 0});
},
},
Instruction::Right => todo!(),
Instruction::Reset => todo!(),
}
}
println!("{instructions:?}");
println!("{light:?}");
}```
This problem is really based around ownership, but I just cant seem to get this to work properly.
This is the compiler error,
|
33 | Instruction::Left => match &mut curr.left {
| ^^^^^^^^^^^^^^
| |
| `curr.left` was mutably borrowed here in the previous iteration of the loop
| first borrow used here, in later iteration of loop```
Im just not sure howto approach this at this stage. Looking for Advice