首页 > 解决方案 > 为什么我的匹配块中需要发送特征?

问题描述

我认为我的问题与Rust Issue 57017 有关

以下代码error: future cannot be sent between threads safely由于future created by async block is not 'Send'源自async fn execute_fail. _ 另一方面,async fn execute_work编译并具有相同的功能和逻辑,execute_fail但方式不太优雅。

async fn stream() -> Result<(), Box<dyn std::error::Error>> {
    Ok(())
}

async fn process() {}

async fn execute_fail() -> Result<(), Box<dyn std::error::Error>> {
    match stream().await {
        Err(err) => {
            return Err(err);
        }
        Ok(()) => {
            process().await;
        }
    }
    Ok(())
}

async fn execute_work() -> Result<(), Box<dyn std::error::Error>> {
    let mut is_success = false;
    match stream().await {
        Err(err) => {
            return Err(err);
        }
        Ok(()) => {
            is_success = true;
        }
    }

    if is_success {
        process().await;
    }
    Ok(())
}

async fn my_fn() {
    tokio::spawn(async {
        if let Err(err) = execute_fail().await {
            panic!("error here");
        }
    });

    tokio::spawn(async {
        if let Err(err) = execute_work().await {
            panic!("error here");
        }
    });
}

给出:

error: future cannot be sent between threads safely
   --> src/lib.rs:39:5
    |
39  |     tokio::spawn(async {
    |     ^^^^^^^^^^^^ future created by async block is not `Send`
    | 
   ::: /playground/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.11.0/src/task/spawn.rs:127:21
    |
127 |         T: Future + Send + 'static,
    |                     ---- required by this bound in `tokio::spawn`
    |
    = help: the trait `Send` is not implemented for `dyn std::error::Error`
note: future is not `Send` as this value is used across an await
   --> src/lib.rs:15:13
    |
10  |     match stream().await {
    |           -------------- has type `Result<(), Box<dyn std::error::Error>>` which is not `Send`
...
15  |             process().await;
    |             ^^^^^^^^^^^^^^^ await occurs here, with `stream().await` maybe used later
16  |         }
17  |     }
    |     - `stream().await` is later dropped here

我想解释一下为什么execute_fail不按原样编译execute_work。编译器注释note: future is not Send as this value is used across an await对我来说没有意义,因为我看不到在 await 中如何使用任何值。

标签: rustlifetimerust-tokiorust-async-std

解决方案


我想解释一下为什么 execute_fail 不能像 execute_work 那样编译。

当你match stream().await基本上工作时:

let v = stream().await;
match v {
   ...
}

所以v在整个匹配过程中都是有效的,这意味着就编译器而言,它的“生命”与process().await调用重叠。值必须Send通过调用才能生存await,因为协程可以在与挂起不同的线程上恢复。

注意:这里的代码可以大大简化:

async fn execute_fail() -> Result<(), Box<dyn std::error::Error>> {
    if let Err(err) = stream().await {
        return Err(err);
    }
    process().await;
    Ok(())
}

甚至

async fn execute_fail() -> Result<(), Box<dyn std::error::Error>> {
    stream().await?;
    process().await;
    Ok(())
}

推荐阅读