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 ? …
Login to see the full exercise.