I've came across this case where I would like to create a struct, that can be modified by a closure that is owned by the struct.
I have never been too deep into closures and capturing environement, nor lifetimes, but I'm wondering why the borrow checker is mad at me. This is what I was hoping for :
struct A {
pub a: usize,
pub b: String,
pub c: C,
}
struct C {
pub modifier: Box<dyn FnMut()>
}
fn main() {
let a = 3;
let b = "Hello, World !".to_string();
let c = C {
modifier: Box::new(|| {
a += 1;
b.push('c');
})
};
let mut my_struct = A {
a, b, c
};
println!("a, b : {}, {}", my_struct.a, my_struct.b);
(my_struct.c.modifier)();
println!("a, b : {}, {}", my_struct.a, my_struct.b);
}
Here, my closure in my C struct does captures my variables a and b, so a and b must live longer than the closure. However, I am storing all of these in the same struct, so they will be dropped at the same time ? meaning that if a or b gets dropped, so does C ?
This does not compile, and it complains that a and b does not live lng enough. We is this so ?
Is there a known pattern that would allow one to achieve such a thing ? (the goal would be that the closure is user-defined, and can modify the struct it is in.)