小编Sim*_* S.的帖子

从闭包调用异步函数

我想要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)

asynchronous future rust async-await

4
推荐指数
1
解决办法
1428
查看次数

标签 统计

async-await ×1

asynchronous ×1

future ×1

rust ×1