Programming Languages
Rust
Subjective
Oct 04, 2025
How does error propagation work with the ? operator?
Detailed Explanation
Error propagation with ?:
• Shorthand for match on Result
• Returns early on Err
• Continues on Ok
• Only works in functions returning Result or Option
• Automatic type conversion with From trait
Example:
use std::fs::File;
use std::io::Read;
fn read_file() -> Result {
let mut file = File::open("file.txt")?; // returns early if Err
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
// Equivalent to:
// match File::open("file.txt") {
// Ok(file) => file,
// Err(e) => return Err(e),
// }
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts