expression

Async function body is deferred

Calling an async function constructs a future, not the completed result. Its body begins when the future is driven. Ordinary argument expressions may already have executed before that construction. The small body here has no pending resource. Expected stdout (not executed): argument constructed inside Ready(7) Common mistake: Expecting the body to execute when an async function is called.

Formal Syntax & Structure

rust syntaxrust
async fn name() -> T { ... }

Working Example

Example Snippetrust
fn main() {    use std::{future::Future, task::{Context, Poll, Wake, Waker}, sync::Arc};    struct Noop;    impl Wake for Noop { fn wake(self: Arc<Self>) {} }    let w = Waker::from(Arc::new(Noop));    let mut cx = Context::from_waker(&w);    async fn work(n: u32) -> u32 { println!("inside"); n + 1 }    let f = work({ println!("argument"); 6 });    println!("constructed");    let mut f = std::pin::pin!(f);    println!("{:?}", f.as_mut().poll(&mut cx));}
Rust Reference