How to store a closure in a struct in Rust?
Hello! I started learning Rust and encountered a problem when trying to store a closure in a struct. I have a simple calculator that should perform different operations depending on the passed closure.
Here's what I'm trying to do:
```rust
struct Calculator {
operation: fn(i32, i32) -> i32,
}
fn main() {
let add = |a, b| a + b;
let calc = Calculator { operation: add };
println!("Result: {}", (calc.operation)(5, 3));
}
```
This code works, but only if I pass a regular function or a closure that doesn't capture variables from the outer environment. As soon as I try to use a closure that captures variables, the compiler gives an error. For example:
```rust
let multiplier = 2;
let multiply = |a, b| a * b * multiplier;
let calc = Cal
No answers yet.
Log in to leave an answer
Blogs