Question Mark Operator
Use ? to propagate errors concisely.
Question Mark Operator
Use ? to propagate errors concisely.
Difficulty
Intermediate
Code
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.