【问题标题】:Why do I need to pin a future before I can await a reference to it?为什么我需要在等待对它的引用之前固定一个未来?
【发布时间】:2022-07-30 19:29:32
【问题描述】:

tokio tutorial for select! 声明:

需要注意的是,要 .await 引用,被引用的值必须被固定或实现 Unpin。

确实,以下代码编译失败:

let fut = example(); // example is an async fn
(&mut fut).await;

带有以下错误消息:

error[E0277]: `from_generator::GenFuture<[static generator@src/main.rs:15:27: 17:2]>` cannot be unpinned
... snip ...
within `impl futures::Future<Output = i32>`, the trait `Unpin` is not implemented for `from_generator::GenFuture<[static generator@src/main.rs:15:27: 17:2]>
... snip ...
note: consider using `Box::pin`

钉住未来解决问题:

let fut = example(); // example is an async fn
tokio::pin!(fut);
(&mut fut).await;

为什么需要固定未来以等待对它的引用?

【问题讨论】:

    标签: rust async-await future


    【解决方案1】:

    通常可以通过思考generated impl Future state machine 的外观来解释有关期货的异常要求。

    在这种情况下,问题如下:示例代码生成的状态机将推断它需要持有一个 reference 来等待它。因为状态机也捕获堆栈,所以它最终会尝试同时保存fut 和对fut 的引用。这是一个self-referential struct,这是有问题的,因为如果您要移动生成的未来,它将使自引用无效。解决这个问题正是 pinning 的 purpose。这就是使用tokio::pin! 修复编译器错误的原因。

    【讨论】:

      猜你喜欢
      • 2021-07-23
      • 1970-01-01
      • 2022-07-12
      • 1970-01-01
      • 2017-03-16
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 2019-12-11
      相关资源
      最近更新 更多