Start Coding

Rust Result<T, E>

The Result<T, E> type is a crucial part of Rust's error handling system. It represents either a successful operation (Ok) or an error (Err).

Understanding Result<T, E>

Result<T, E> is an enum with two variants:

  • Ok(T): Represents a successful operation, containing a value of type T
  • Err(E): Represents an error, containing an error value of type E

Basic Usage

Here's a simple example of using Result:


fn divide(x: f64, y: f64) -> Result<f64, String> {
    if y == 0.0 {
        Err("Division by zero".to_string())
    } else {
        Ok(x / y)
    }
}

fn main() {
    match divide(10.0, 2.0) {
        Ok(result) => println!("Result: {}", result),
        Err(error) => println!("Error: {}", error),
    }
}
    

Working with Result

Rust provides several methods to work with Result values:

  • is_ok() and is_err(): Check if the Result is Ok or Err
  • unwrap(): Returns the Ok value or panics if it's an Err
  • expect(): Similar to unwrap, but with a custom panic message
  • unwrap_or(): Returns the Ok value or a default value if it's an Err

Error Propagation

The ? operator simplifies error propagation in Rust. It automatically returns the error if the Result is an Err, or unwraps the Ok value.


fn process_data() -> Result<String, io::Error> {
    let data = read_file("data.txt")?;
    Ok(process(data))
}
    

Best Practices

  • Use Result for operations that can fail
  • Avoid using unwrap() in production code
  • Implement custom error types for complex error handling
  • Use the ? operator for concise error propagation

Related Concepts

To deepen your understanding of error handling in Rust, explore these related topics:

By mastering Result<T, E>, you'll write more robust and error-resistant Rust code. It's a fundamental concept in Rust's approach to safe and reliable programming.