I have this code, where a method that takes &mut self has this in the beginning:
fn run_instruction(&mut self) -> Result<(), RuntimeError> {
let last_frame = self
.stack_frames
.last_mut()
.expect("tried to run without any stack frames");
let function: &Function = match last_frame.function {
FunctionRef::MainFunction => &self.program.main_function,
FunctionRef::Function(i) => &self.program.functions[i]
};
Those last 4 lines - turned out I needed similar behavior in other methods, so I decided to put that match expression into its own method and re-use that:
fn get_function(&self, function_ref: &FunctionRef) -> &Function {
match function_ref {
FunctionRef::MainFunction => &self.program.main_function,
FunctionRef::Function(i) => &self.program.functions[*i]
}
}
//////////////
let last_frame = self
.stack_frames
.last_mut()
.expect("tried to run without any stack frames");
let function: &Function = self.get_function(&last_frame.function);