Search code examples
rustrust-tokio

What is the smallest feature set to enable polling a future with Tokio?


I want to poll an async function:

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

I am currently activating all features:

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

which of those are necessary?

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

Solution

  • To enable polling a future with Tokio, you need a 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(())
    }
    

    If you want to use the tokio::main macro:

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

    If you want the exact syntax you've specified (which is not the "smallest feature set to enable polling a future with Tokio"), then the runtime error guides you:

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

    See also: