Error Handling Patterns
Result Match
Handling Success and Failure
Result represents either Ok(value) or Err(error). Matching both cases makes the success and failure paths explicit.
Program
Play the program to parse selected text and build a label from the Result.
result_match.rs
fn main() {
let text = ;
let parsed = text.parse::<i32>();
let label = match parsed {
Ok(value) => format!("ok:{value}"),
Err(_) => "error".to_string(),
};
println!("{label}");
}
fn main() {
let text = ;
let parsed = text.parse::<i32>();
let label = match parsed {
Ok(value) => format!("ok:{value}"),
Err(_) => "error".to_string(),
};
println!("{label}");
}
fn main() {
let text = ;
let parsed = text.parse::<i32>();
let label = match parsed {
Ok(value) => format!("ok:{value}"),
Err(_) => "error".to_string(),
};
println!("{label}");
}
Result
`Result<T, E>` is either `Ok(T)` or `Err(E)`.
match
`match parsed` handles both success and error cases.
error path
The `Err(_)` arm ignores the error detail and returns a stable label.