Handling Result<T, E> in Rust.


Ways to Handle Result<T, E>

1. ? — Propagate error (most common)

fn do_stuff() -> Result<(), Error> {
    let data = might_fail()?;  // Returns early if Err
    Ok(())
}

2. match — Handle both cases explicitly

match client.fetch_exchange_info().await {
    Ok(info) => println!("{:#?}", info),
    Err(e) => eprintln!("Failed: {}", e),
}

3. if let — Only care about one case

if let Ok(info) = client.fetch_exchange_info().await {
    println!("{:#?}", info);
}

4. .unwrap() / .expect() — Crash on error

let info = result.unwrap();           // Panics with generic message
let info = result.expect("API down"); // Panics with your message

5. .unwrap_or() / .unwrap_or_default() — Fallback value

let count = result.unwrap_or(0);         // Use 0 if error
let name = result.unwrap_or_default();   // Use String::default() ("")

6. .unwrap_or_else() — Fallback with logic

let info = result.unwrap_or_else(|e| {
    eprintln!("Error: {}", e);
    ExchangeInfo::default()
});

7. .ok() — Convert to Option, discard error

let maybe_info: Option<ExchangeInfo> = result.ok();

8. .map() / .map_err() — Transform inner value

let lengths = result.map(|info| info.symbols.len());
let custom_err = result.map_err(|e| MyError::from(e));