天天看点

013 Rust 异步编程,Send trait 相关

async fn Future是否为Send的取决于是否在.await点上保留非Send类型。编译器尽其所能地估计值在.await点上的保存时间。

示例

  • 源码
use std::rc::Rc;

#[derive(Default)]
struct NotSend(Rc<()>);

async fn bar() {}

async fn foo() {
  NotSend::default();
  bar().await;
}

fn required_send(_: impl Send) {}

fn main() {
  required_send(foo());
}      
  • 说明
async fn foo() {
  let x = NotSend::default();
  bar().await;
}      
  • 原因分析
  • 解决方式
async fn foo() {
    {
        let x = NotSend::default();
    }
    bar().await;
}      

继续阅读