Skip to content

Instantly share code, notes, and snippets.

@dgehriger
Created November 14, 2024 12:51
Show Gist options
  • Save dgehriger/4d9ca4e4938f61b6497849eca370a4ce to your computer and use it in GitHub Desktop.
Save dgehriger/4d9ca4e4938f61b6497849eca370a4ce to your computer and use it in GitHub Desktop.
Option and Result in Rust

For Option<T>

Instead of using unwrap(), you can handle Option types in the following ways:

  1. Using if let:

    let maybe_value: Option<i32> = Some(42);
    
    if let Some(value) = maybe_value {
        println!("Got a value: {}", value);
    } else {
        eprintln!("Value was None, handling the None case here.");
    }
  2. Using unwrap_or or unwrap_or_else to provide a fallback value or handle cases gracefully:

    let value = maybe_value.unwrap_or(0); // Returns 0 if None
    let value = maybe_value.unwrap_or_else(|| {
        eprintln!("Value was None, computing a default...");
        compute_default_value()
    });

For Result<T, E>

For Result types, there are a few good alternatives to unwrap():

  1. Using if let to handle the Ok case, while dealing with the Err case as needed:

    let result: Result<i32, &str> = Ok(42);
    
    if let Ok(value) = result {
        println!("Operation succeeded with value: {}", value);
    } else {
        eprintln!("Operation failed, handling the error case here.");
    }
  2. Using unwrap_or_else to handle errors directly and provide fallback values:

    let value = result.unwrap_or_else(|e| {
        eprintln!("Error encountered: {}", e);
        0 // Fallback value in case of an error
    });
  3. Using the ? operator to propagate errors in functions that return Result. The ? operator will return an Err early if encountered, which is useful in functions that can fail. Here’s an example:

    fn calculate() -> Result<i32, Error> {
        let a = get_value()?; // Propagates any error from get_value()
        let b = compute_something(a)?;
        Ok(b)
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment