Puzzle 22: Explanation
Let’s learn how Rust handles asynchronous tasks in a program.
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(()) }
Calling async functions in Rust
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
async
keyword.
...