Rust result
Created By: chatGPT
Rust provides a powerful enum called
Result
for error handling. It allows you to define a function's outcome, whether it is successful or an error. The Result
type is defined with two variants: Ok
for success and Err
for failure. This helps in writing robust applications that handle errors gracefully.enum Result<T, E> {
Ok(T),
Err(E),
}
// Example of a function returning Result
fn divide(num: f64, denom: f64) -> Result<f64, String> {
if denom == 0.0 {
Err(String::from("Cannot divide by zero"))
} else {
Ok(num / denom)
}
}
You can use pattern matching to handle the cases of
Result
. This approach allows you to specify different actions based on whether the function succeeded or failed. Pattern matching can be done easily with a match
statement.fn main() {
let result = divide(10.0, 2.0);
match result {
Ok(value) => println!("Result: {}", value),
Err(error) => println!("Error: {}", error),
}
}
In addition, the
Result
type comes with various utility methods that enhance its functionality. Some of these methods include unwrap()
, expect()
, and map()
. Using unwrap()
will return the value if it's Ok
, but will panic if it's an Err
. It's advisable to use it cautiously as it can cause the application to terminate unexpectedly.let value = divide(10.0, 0.0).unwrap(); // This will panic
// Instead, use expect to provide a custom panic message
let value = divide(10.0, 0.0).expect("Failed to divide");
For a more controlled error handling, consider using
unwrap_or()
which returns a default value in case of an error instead of panicking.let value = divide(10.0, 0.0).unwrap_or(0.0); // Returns 0.0 instead of panicking
println!("Value: {}", value);