intermediateError Handling
Result Basic
Handle errors with Result<T, E> type.
Result Basic
Handle errors with Result
Difficulty
Intermediate
Code
rust
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
This example demonstrates how to use result basic in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the error-handling category to build a complete understanding of this topic.