The Result Type
Result is Rust's way of saying an operation either worked and gives you an answer, or failed and tells you why.What Is Result
Result<T, E> is an enum with two variants: Ok(value) for success carrying a T, and Err(error) for failure carrying an E. It's the standard way Rust represents fallible operations.
Example: What Is Result
fn divide(a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 {
Err(String::from("division by zero"))
} else {
Ok(a / b)
}
}
fn main() {
println!("{:?}", divide(10.0, 2.0));
}
Login to try C/C++/Java/PHP code in the editor
Matching on Result
match lets you explicitly handle both the success and failure cases of a Result, extracting the value or the error as needed.
Example: Matching on Result
fn divide(a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 {
Err(String::from("division by zero"))
} else {
Ok(a / b)
}
}
fn main() {
match divide(5.0, 0.0) {
Ok(value) => println!("Result: {}", value),
Err(e) => println!("Error: {}", e),
}
}
Login to try C/C++/Java/PHP code in the editor
Parsing Returns a Result
Many standard library operations that can fail, like parsing a string into a number, return a Result so the caller must decide how to handle a malformed input.
Example: Parsing Returns a Result
fn main() {
let input = "42";
let parsed: Result<i32, _> = input.parse();
match parsed {
Ok(n) => println!("Parsed number: {}", n),
Err(_) => println!("Could not parse"),
}
}
Login to try C/C++/Java/PHP code in the editor
Result vs Option
Option signals whether a value is present at all, while Result additionally carries information about why an operation failed, making it the better choice whenever the reason for failure matters.
Example: Result vs Option
fn safe_divide(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
Err(String::from("cannot divide by zero"))
} else {
Ok(a / b)
}
}
fn main() {
println!("{:?}", safe_divide(10, 2));
println!("{:?}", safe_divide(10, 0));
}
Login to try C/C++/Java/PHP code in the editor
- Ignoring a
Resultreturned by a function -- the compiler warns about an unusedResultsince errors could be silently dropped. - Assuming
ResultandOptionare interchangeable --Resultcarries error information, whileOptionjust signals absence. - Trying to use the
Okvalue directly without matching or unwrapping theResultfirst.
Result<T, E>represents either success (Ok(value)) or failure (Err(error)).- Functions that can fail, like parsing or file I/O, typically return a
Resultinstead of panicking directly. matchis the most explicit way to handle both theOkandErrcases of aResult.- Rust's compiler warns when a
Resultis left unused, nudging you to handle potential errors.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: