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
This example demonstrates how to use question mark operator 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.