启用 Tokio 投票未来的最小功能集是什么?

问题描述

我想轮询一个异步函数:

#[tokio::main]
async fn main() -> Result<(),Box<dyn std::error::Error>> {
    some_function().await;
}

我目前正在激活所有功能:

tokio = { version = "1.4.0",features = ["full"] }

哪些是必要的?

full = [
  "fs","io-util","io-std","macros","net","parking_lot","process","rt","rt-multi-thread","signal","sync","time",]

解决方法

要使用 Tokio 对未来进行轮询,您需要一个 Runtime

仅在板条箱功能 rt 上支持此功能。

[dependencies]
tokio = { version = "1.4.0",features = ["rt"] }
fn main() -> Result<(),Box<dyn std::error::Error>> {
    tokio::runtime::Builder::new_current_thread()
        .build()
        .unwrap()
        .block_on(some_function())
}

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

如果您想使用 tokio::main 宏:

这仅在板条箱功能 rtmacros 上受支持。

[dependencies]
tokio = { version = "1.4.0",features = ["rt","macros"] }
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(),Box<dyn std::error::Error>> {
    some_function().await
}

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

如果您想要指定的精确语法(这不是“启用 Tokio 轮询未来的最小功能集”),那么运行时错误会指导您:

默认的运行时风格是 multi_thread,但 rt-multi-thread 功能被禁用。

[dependencies]
tokio = { version = "1.4.0","rt-multi-thread","macros"] }
#[tokio::main]
async fn main() -> Result<(),Box<dyn std::error::Error>> {
    Ok(())
}

另见:

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...