Skip to content
← Dist
rusttokio_match.rsrusttokioasync

Match a Tokio Result

Pattern for matching Ok/Err from an async Tokio call without losing the error context.

Common shape when a Tokio task or I/O call returns Result — keep success on the happy path and map errors once.

use std::time::Duration;

use tokio::time::timeout;

#[derive(Debug)]
pub enum FetchError {
    TimedOut,
    Io(std::io::Error),
}

pub async fn fetch_with_deadline(url: &str) -> Result<String, FetchError> {
    let work = async {
        // stand-in for reqwest / hyper / custom client
        Ok::<_, std::io::Error>(format!("body from {url}"))
    };

    match timeout(Duration::from_secs(2), work).await {
        Ok(Ok(body)) => Ok(body),
        Ok(Err(e)) => Err(FetchError::Io(e)),
        Err(_elapsed) => Err(FetchError::TimedOut),
    }
}

#[tokio::main]
async fn main() {
    match fetch_with_deadline("https://example.com").await {
        Ok(body) => println!("ok: {body}"),
        Err(FetchError::TimedOut) => eprintln!("request timed out"),
        Err(FetchError::Io(e)) => eprintln!("io failed: {e}"),
    }
}