Question is simple - how to force struct to be moved into a closure and not just its field copied?
In my case I receive struct from the C code with some data and a release function. I need to release data only after callback is gets triggered.
struct Abc {
ptr: usize,
free: fn(usize),
}
impl Drop for Abc {
fn drop(&mut self) {
(self.free)(self.ptr);
}
}
fn test(data: Abc) -> impl Fn() -> String {
move || {
format!("{}", data.ptr) // do something with ptr
}
}
fn main() {
let abc = Abc {
ptr: 10,
free: |_| {},
};
let closure = test(abc);
closure();
closure();
closure();
}
The problem is that Rust for some reason copies the value of ptr and drops struct before closure is getting called instead of keeping struct alive until closure dies itself.
When I inspect a closure, I can see that indeed only a field gets copied instead of the struct.