Rust Systems & Tokio (50 Qs)•Part 1: Basic & Foundational Concepts (Junior / Entry-Level)
How does the question mark (`?`) operator work in error handling?
junior LevelCode ExamplerustBasic
In Simple Words:
The ? operator provides ergonomic error propagation:
- If the result is
Ok(val), it unwraps and returnsval. - If the result is
Err(e), it returns early from the current function immediately, passing the error up the call stack! - Automatically converts error types if an implementation of
Fromexists.
rust
use std::fs::File;
use std::io::{self, Read};
fn read_username_from_file() -> Result<String, io::Error> {
let mut file = File::open("username.txt")?; // Early return on error!
let mut username = String::new();
file.read_to_string(&mut username)?;
Ok(username)
}