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

Gat*_*ito 9 rust rust-tokio

我想轮询一个异步函数:

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

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

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

其中哪些是必要的?

tokio = { version = "1.4.0", features = ["full"] }
Run Code Online (Sandbox Code Playgroud)

She*_*ter 17

要启用 Tokio 轮询未来,您需要一个Runtime.

仅板条箱功能支持此功能rt

[dependencies]
tokio = { version = "1.4.0", features = ["rt"] }
Run Code Online (Sandbox Code Playgroud)
[dependencies]
tokio = { version = "1.4.0", features = ["rt"] }
Run Code Online (Sandbox Code Playgroud)

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

rt仅板条箱功能支持此功能macros

[dependencies]
tokio = { version = "1.4.0", features = ["rt", "macros"] }
Run Code Online (Sandbox Code Playgroud)
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(())
}
Run Code Online (Sandbox Code Playgroud)

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

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

[dependencies]
tokio = { version = "1.4.0", features = ["rt", "rt-multi-thread", "macros"] }
Run Code Online (Sandbox Code Playgroud)
[dependencies]
tokio = { version = "1.4.0", features = ["rt", "macros"] }
Run Code Online (Sandbox Code Playgroud)

也可以看看:

  • @Gatonito 要使用 `tokio::main` 属性,您需要 `"macros"` 功能,并且默认运行时是多线程的,因此您需要 `"rt-multi-thread"` 而不是 `"rt"`。 (2认同)