我想要await
一个async
在迭代器中使用的闭包内的函数。需要闭包的函数在结构体实现中被调用。我无法弄清楚如何做到这一点。
这段代码模拟了我正在尝试做的事情:
struct MyType {}
impl MyType {
async fn foo(&self) {
println!("foo");
(0..2).for_each(|v| {
self.bar(v).await;
});
}
async fn bar(&self, v: usize) {
println!("bar: {}", v);
}
}
#[tokio::main]
async fn main() {
let mt = MyType {};
mt.foo().await;
}
Run Code Online (Sandbox Code Playgroud)
显然,这将不起作用,因为闭包不是async
,给我:
error[E0728]: `await` is only allowed inside `async` functions and blocks
--> src/main.rs:8:13
|
7 | (0..2).for_each(|v| {
| --- this is not `async`
8 | self.bar(v).await;
| ^^^^^^^^^^^^^^^^^ only allowed inside `async` …
Run Code Online (Sandbox Code Playgroud)