Concept Flow - Handling errors with match
Start
Call function that may error
match on Result
Use value
End
This flow shows calling a function that returns a Result, then using match to handle success (Ok) or error (Err) cases.
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() { match divide(10, 0) { Ok(result) => println!("Result: {}", result), Err(e) => println!("Error: {}", e), } }
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Call divide(10, 0) | b == 0 is true | Returns Err("Cannot divide by zero") |
| 2 | match on Result | Result is Err | Go to Err branch |
| 3 | Print error message | Prints "Error: Cannot divide by zero" | Output to console |
| 4 | End | No more code | Program ends |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| a | 10 | 10 | 10 | 10 | 10 |
| b | 0 | 0 | 0 | 0 | 0 |
| result | N/A | Err("Cannot divide by zero") | Err("Cannot divide by zero") | Err("Cannot divide by zero") | Err("Cannot divide by zero") |
| e | N/A | N/A | "Cannot divide by zero" | "Cannot divide by zero" | "Cannot divide by zero" |
Handling errors with match in Rust:
- Use functions returning Result<T, E>
- Use match to check Result:
match result {
Ok(val) => handle success,
Err(e) => handle error,
}
- This cleanly separates success and error handling.match statement do when used with a Result type in Rust?match with Resultmatch statement is used to check the two possible states of a Result: Ok for success and Err for failure.Ok and Err, you can write code to handle success and error separately, making the program safe and clear.Ok or Err and lets you handle each case. -> Option DResult<T, E> named res and print "Success" if Ok?Ok(_) and Err(_) with arrows => to separate patterns from actions.Ok and "Error" on Err, which matches the question requirement.let res: Result<i32, &str> = Err("fail");
match res {
Ok(val) => println!("Value: {}", val),
Err(e) => println!("Error: {}", e),
}res is assigned Err("fail"), so it represents an error.match will go to the Err(e) arm and print "Error: fail".let res: Result<i32, &str> = Ok(10);
match res {
Ok(val) => println!("Value: {}", val),
Err => println!("Error occurred"),
}Result must pattern match with parentheses, so Err should be Err(_) or Err(e).Err without parentheses, which is invalid syntax and causes a compile error.Result<i32, String>. Inside, you try to parse a string to an integer. Using match, how do you handle the parsing result to return Ok(number) if successful or Err with a custom message if it fails?parse() method returns Result<T, E>, so matching on it lets us handle success and failure.Ok(n), return Ok(n) to propagate success. On Err(_), return Err with a custom error message as a String.Pass the test and this pattern moves unknown