expression
Async result propagation with ?
An async function can return Result in its output. Await first obtains that Result, then the question-mark operator can return an error from the enclosing async body. The pending state remains separate from the completed error state. Expected stdout (not executed): Ready(Ok(14)) true Common mistake: Applying ? to a future before awaiting its Result output.
Formal Syntax & Structure
rust syntaxrust
let value = operation().await?;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 parse(s: &str) -> Result<u32, std::num::ParseIntError> { s.parse() } async fn twice(s: &str) -> Result<u32, std::num::ParseIntError> { Ok(parse(s).await? * 2) } let mut a = std::pin::pin!(twice("7")); let mut b = std::pin::pin!(twice("x")); println!("{:?}", a.as_mut().poll(&mut cx)); println!("{}", matches!(b.as_mut().poll(&mut cx), Poll::Ready(Err(_))));}