【发布时间】:2021-12-28 06:40:18
【问题描述】:
我正在尝试将异步函数作为参数传递。异步函数接受一个引用,因为它是争论的。
use std::future::Future;
async fn f(x: &i32) -> i32 {
todo!()
}
async fn g<F, Fut>(f: F)
where
F: Send + Sync + 'static + for<'a> Fn(&'a i32) -> Fut,
Fut: Future<Output = i32> + Send + Sync,
{
// let x = 3;
// f(&x).await;
}
#[tokio::main]
async fn main() {
g(f).await;
}
但是我有编译错误。
error[E0308]: mismatched types
--> src/main.rs:18:5
|
18 | g(f).await;
| ^ lifetime mismatch
|
= note: expected associated type `<for<'_> fn(&i32) -> impl Future<Output = i32> {f} as FnOnce<(&i32,)>>::Output`
found associated type `<for<'_> fn(&i32) -> impl Future<Output = i32> {f} as FnOnce<(&'a i32,)>>::Output`
= note: the required lifetime does not necessarily outlive the empty lifetime
note: the lifetime requirement is introduced here
--> src/main.rs:9:55
|
9 | F: Send + Sync + 'static + for<'a> Fn(&'a i32) -> Fut,
| ^^^
For more information about this error, try `rustc --explain E0308`.
error: could not compile `test-async-tokio` due to previous error
这里Fut为什么要引入lifetime?
如何指定这段代码的生命周期?
最好的问候!
【问题讨论】:
-
如果您在 trait bound 中更改为像
g<'a, ...>这样的适当生命周期参数而不是for<'a>,则错误会稍微清晰一些:x借用生命周期'a但在末尾删除范围。仍然试图弄清楚为什么这是一个问题,因为你等待它...... -
如你所说,我已更改为终身注释。但是
g使用了一个局部变量x。并且对x的引用不能限制为'a。F: Send + Sync + 'static + Fn(&'a i32) -> Fut, -
This Comment 效果很好。我可以将异步函数移动到结构包装器。但这有点复杂。
标签: asynchronous rust arguments lifetime