I store a FnOnce
closure inside a struct inside an enum (Rust Playground):
pub struct ClosureContainer {
closure: Box<dyn FnOnce(i32) -> i32>,
}
pub enum MathOperation {
DoNothing,
RunOperation(ClosureContainer),
}
impl MathOperation {
pub fn doMath(&self, input: i32) -> i32 {
match self {
MathOperation::DoNothing => input,
MathOperation::RunOperation(closureContainer) => (closureContainer.closure)(input),
}
}
}
fn main() {
let f = Box::new(move |input: i32| 4 * input);
let closureContainer = ClosureContainer { closure: f };
let operation = MathOperation::RunOperation(closureContainer);
println!("{}", operation.doMath(5));
}
When I try to build, I get this error:
error[E0507]: cannot move out of `closureContainer.closure` which is behind a shared reference
--> src/main.rs:14:62
|
14 | MathOperation::RunOperation(closureContainer) => (closureContainer.closure)(input),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ move occurs because `closureContainer.closure` has type `Box<dyn FnOnce(i32) -> i32>`, which does not implement the `Copy` trait
How do I set things up so that I can call this function?