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

What is the smallest feature set to enable polling a future with 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

This is supported on crate feature rt only.

[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宏:

This is supported on crate features rt and macros only.

[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(())
}

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

The default runtime flavor is multi_thread, but the rt-multi-thread feature is disabled.

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

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

另请参阅: