Introduction
The Result enum helps your program handle success or failure clearly. It tells you if something worked or if there was an error.
The Result enum helps your program handle success or failure clearly. It tells you if something worked or if there was an error.
enum Result<T, E> {
Ok(T),
Err(E),
}T is the type for a successful value.
E is the type for an error value.
Result with an integer on success and a string on error.let success: Result<i32, &str> = Ok(10); let failure: Result<i32, &str> = Err("Oops");
Ok with the division result or Err with an error message.fn divide(a: i32, b: i32) -> Result<i32, String> { if b == 0 { Err(String::from("Cannot divide by zero")) } else { Ok(a / b) } }
This program tries to divide numbers safely. It prints the result if successful or an error message if not.
fn divide(a: i32, b: i32) -> Result<i32, String> { if b == 0 { Err(String::from("Cannot divide by zero")) } else { Ok(a / b) } } fn main() { let result = divide(10, 2); match result { Ok(value) => println!("Success: {}", value), Err(e) => println!("Error: {}", e), } let fail = divide(5, 0); match fail { Ok(value) => println!("Success: {}", value), Err(e) => println!("Error: {}", e), } }
You can use match to check if a Result is Ok or Err.
Using Result helps avoid crashes by handling errors properly.
Result shows success or failure clearly.
Use Ok for success and Err for errors.
Handle Result with match to respond to each case.
Result enum in Rust represent?ResultResult is used to show if an operation succeeded or failed.Ok means success, Err means failure or error.Ok) or failure (Err) -> Option CResult = success or failure [OK]Result with a success value of 10?Ok, so Ok(10) is correct.Result, so Ok(10) matches i32 for success.fn divide(a: i32, b: i32) -> Result {
if b == 0 {
Err(String::from("Divide by zero"))
} else {
Ok(a / b)
}
}
fn main() {
match divide(10, 2) {
Ok(result) => println!("Result: {}", result),
Err(e) => println!("Error: {}", e),
}
}divide(10, 2) means b is 2, not zero, so it returns Ok(10 / 2) which is Ok(5).match sees Ok(5), so it prints Result: 5.Result:fn get_number(flag: bool) -> Result {
if flag {
Ok(42)
} else {
Err(42)
}
}Result<i32, String>, so Ok must hold i32 and Err must hold String.Err(42)42 is an integer, but Err expects a String. This causes a type mismatch.Err variant has wrong type; should be a String -> Option AResult handling?let strings = vec!["10", "abc", "20", "xyz"];
// Fill in the blank:
let numbers: Vec<i32> = strings.iter()
.map(|s| s.parse::<i32>())
.__________;
println!("{:?}", numbers);parse returns Results.parse::<i32>() returns Result<i32, _>, so we get an iterator of Results.filter_map(Result::ok) to keep only successesfilter_map(Result::ok) extracts the Ok values and skips errors, then collect() gathers them into a vector.Pass the test and this pattern moves unknown