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).
Result<T, E>
is an enum with two variants:
Ok(T)
: Represents a successful operation, containing a value of type TErr(E)
: Represents an error, containing an error value of type EHere'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),
}
}
Rust provides several methods to work with Result
values:
is_ok()
and is_err()
: Check if the Result is Ok or Errunwrap()
: Returns the Ok value or panics if it's an Errexpect()
: Similar to unwrap, but with a custom panic messageunwrap_or()
: Returns the Ok value or a default value if it's an ErrThe ?
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))
}
Result
for operations that can failunwrap()
in production code?
operator for concise error propagationTo 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.