RRust By Example
intermediateError Handling

Question Mark Operator

Use ? to propagate errors concisely.

Question Mark Operator

Use ? to propagate errors concisely.

Difficulty

Intermediate

Code

rust
use std::fs;
use std::io;

fn read_username() -> Result<String, io::Error> {
    let content = fs::read_to_string("username.txt")?;
    Ok(content.trim().to_string())
}

fn main() {
    match read_username() {
        Ok(name) => println!("Hello, {}!", name),
        Err(e) => println!("Error: {}", e),
    }
}

Explanation

The ? operator propagates errors concisely.

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