// Created on savesnippets.com · https://savesnippets.com/WftL4haAZh3AJJ use tokio::time::{sleep, timeout, Duration}; async fn slow() -> i32 { sleep(Duration::from_secs(5)).await; 42 } #[tokio::main] async fn main() { match timeout(Duration::from_secs(2), slow()).await { Ok(value) => println!("got {value}"), Err(_) => println!("timed out"), } // Composed with ? — works because timeout returns Result let result: Result = timeout(Duration::from_millis(100), async { 7 }).await; println!("{:?}", result); // Ok(7) }