sssilver
sssilver

Reputation: 2869

Spawning a task in tokio from tokio::test

I have roughly the following tokio::main:

#[tokio::main]
pub async fn my_tokio_main() {
    let addr = "[::1]:9002";
    let listener = TcpListener::bind(&addr).await.expect("Can't listen");

    while let Ok((stream, _)) = listener.accept().await {
        // Handle the connection
    }
}

With roughly the following test:

#[tokio::test]
async fn test_hello() {
    task::spawn(my_tokio_main());
//              ^^^^^^^^^^^^^^^ `()` is not a future

}

However, when building the test, the compiler complains that () is not a future.

My understanding is that because my_tokio_main() is async, then it does return a future. Why is the compiler complaining here?

Upvotes: 1

Views: 1886

Answers (1)

Matthias247
Matthias247

Reputation: 10426

You have the #[tokio::main] attribute on the main function. This attribute will transform the function into a synchronous function, which creates a tokio runtime and will call runtime.block_on(future) where future is the result of the defined async function.

Therefore the actually generated my_tokio_main is synchronous. You could seperate the tokio::main wrapper and the async function definition in order to call into the async function from another async function.

Upvotes: 3

Related Questions