It is possible to modify a function argument in-place with the following code snippet:
let mut foo = 1;
let mut fun: Box<dyn FnMut(&mut i32) -> _> = Box::new(|f| {
*f += 1;
});
fun(&mut foo);
assert_eq!(foo, 2);
However, I have the case where the function fun needs to return a future which modifies the argument once the future gets awaited. Basically I have the following scenario:
let mut foo = 1;
assert_eq!(foo, 1);
let mut fun: Box<dyn FnMut(&mut i32) -> _> = Box::new(|f| {
async move {
*f += 1;
}
});
fun(&mut foo).await;
assert_eq!(foo, 2);
But this gives the compile error:
error: lifetime may not live long enough
--> src/main.rs:7:9
|
6 | let mut fun: Box<dyn FnMut(&mut i32) -> _> = Box::new(|f| {
| -- return type of closure `impl Future<Output = ()>` contains a lifetime `'2`
| |
| has type `&'1 mut i32`
7 | / async move {
8 | | *f += 1;
9 | | }
| |_________^ returning this value requires that `'1` must outlive `'2`
error: could not compile `playground` due to previous error
I am not sure how to annotate lifetimes in my code snippet above. I have tried Box<dyn FnMut(&'static mut i32) -> _>, but this gives that foo does not live long enough.
Is there a way to get this working?