RRust By Example
intermediateError Handling

Result Basic

Handle errors with Result<T, E> type.

Result Basic

Handle errors with Result type.

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

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.

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Error Handling Examples