Asynchronous programming in Rust is implemented through Future — an object representing a computation whose result will be available in the future. Functions declared with async fn return an anonymous generator struct that implements the Future trait. To run asynchronous code, a runtime (such as Tokio or async-std) is required, as the standard library does not include a built-in event loop.
Key features of Rust:
Example:
use tokio::time::sleep; use std::time::Duration; async fn foo() { println!("Hello"); sleep(Duration::from_secs(1)).await; println!("World!"); } #[tokio::main] async fn main() { foo().await; }
Can an asynchronous function in Rust be executed immediately upon calling? Why?
Answer:
No. Calling async fn returns not a result, but an object of type Future (state machine). To actually execute it, you need to call .await or pass the Future to a runtime. The call only creates a task description but does not execute it.
Example:
async fn answer() -> u32 { 42 } let fut = answer(); // this does not execute, just creates a future let result = fut.await; // execution starts here
Story
.await anywhere. As a result, the main threads were executing synchronously, leading to performance degradation and a threefold increase in response time.Story
Story
One of the team members forgot about the Send/Sync limitations on the types used within Future. When trying to share future across threads, the application crashed with a compilation error requiring Send to be implemented for a certain struct, necessitating a reevaluation of the state storage architecture.