Result Basic
Handle errors with Result<T, E> type.
Result Basic
Handle errors with Result
Difficulty
Intermediate
Code
use std::num::ParseIntError;
fn parse_age(input: &str) -> Result<u32, ParseIntError> {
input.parse::<u32>()
}
fn main() {
match parse_age("25") {
Ok(age) => println!("age: {}", age),
Err(e) => println!("error: {}", e),
}
match parse_age("not a number") {
Ok(age) => println!("age: {}", age),
Err(e) => println!("error: {}", e),
}
}Explanation
Result represents success or failure.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the error-handling category to build a complete understanding of this topic.