Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use async/await in Rust when you can't make main function async

I have a function to download a file which is async:

async fn download_file() {
    fn main() {
        let resp = reqwest::blocking::get("https://sh.rustup.rs").expect("request failed");
        let body = resp.text().expect("body invalid");
        let mut out = File::create("rustup-init.sh").expect("failed to create file");
        io::copy(&mut body.as_bytes(), &mut out).expect("failed to copy content");
    }
}

I want to call this function to download a file and then await it when I need it.
But the problem is if I do it like this, I get an error:

fn main() {
    let download = download_file();
    // Do some work
    download.await; // `await` is only allowed inside `async` functions and blocks\nonly allowed inside `async` functions and blocks
    // Do some work
}

So I have to make the main function async, but when I do that I get another error:

async fn main() { // `main` function is not allowed to be `async`\n`main` function is not allowed to be `async`"
    let download = download_file();
    // Do some work
    download.await;
    // Do some work
}

So how can I use async and await
Thanks for helping

like image 353
NightmareXD Avatar asked Sep 02 '25 16:09

NightmareXD


1 Answers

The most commonly used runtime, tokio, provides an attribute macro so that you can make your main function async:

#[tokio::main]
async fn main() {
    let download = download_file().await;
}

In case you don't have a dependency on tokio just yet, add the following to your Cargo.toml:

tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
like image 197
msrd0 Avatar answered Sep 05 '25 15:09

msrd0