Puzzle 22: Explanation
Explore how asynchronous functions in Rust work by creating futures that represent tasks ready for execution. Learn the two-step process to run async functions and understand how to use await, spawn, join!, and select! for managing concurrency effectively.
We'll cover the following...
Test it out
Press “Run” to see the output of the code.
async fn hello() {
println!("Hello, World!")
}
#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
hello();
Ok(())
}Explanation
Our program’s executor performs the tasks that run until they yield control back to the task queue. Tasks only yield once they return a value or error, call another asynchronous task, finish execution, or call yield_now. Tasks also don’t start when we call them. When we call a function decorated with the async keyword, it returns a future.
Calling an async decorated function doesn’t execute the function. Instead, it packages it up for future execution.
Let’s take a look at the life cycle of an asynchronous function:
- Create an asynchronous function, using the
asynckeyword.
...