可以使用以下代码片段就地修改函数参数:
let mut foo = 1;
let mut fun: Box<dyn FnMut(&mut i32) -> _> = Box::new(|f| {
*f += 1;
});
fun(&mut foo);
assert_eq!(foo, 2);
然而,我遇到这样的情况,函数fun
需要返回一个将来,一旦等待将来,它就会修改参数.基本上,我有以下情景:
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);
但这会产生编译错误:
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
我不确定如何在上面的代码片段中注释生命周期.我试过Box<dyn FnMut(&'static mut i32) -> _>
次,但这说明foo
次的生命周期 不够长.
有没有办法让这件事起作用?