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
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"] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With