The ? Operator
Medium
+3 pts
Error Handling
4/4
Chaining .and_then() works, but gets verbose. Rust's ? operator is syntactic sugar for error propagation.
Before: manual matching
fn read_config() -> Result<Config, Error> {
let file = match File::open("config.txt") {
Ok(f) => f,
Err(e) => return Err(e),
};
let contents = match read_to_string(file) {
Ok(s) => s,
Err(e) => return Err(e),
};
parse_config(&contents)
}
After: with ?
fn read_config() -> Result<Config, Error> {
let file = File::open("config.txt")?;
let contents = read_to_string(file)?;
parse_config(&contents)
}
The ? does exactly what the match did: if Ok, unwrap the value; if Err, return early with the error.
Python comparison
In Python, exceptions propagate automatically:
def read_config():
file = open("config.txt") # raises if fails
contents = file.read() # raises if fails
return parse_config(contents)
Rust's ? gives you the same concise code, but the error handling is explicit in the return type.
? works with Option too
…Login to see the full exercise.