Propagating Errors with ?
The try-operator ? is used to return errors to the caller. It lets you turn the common
match some_expression { Ok(value) => value, Err(err) => return Err(err), }
into the much simpler
some_expression?
We can use this to simplify our error handing code:
1. use std::fs;
2. use std::io::{self, Read};
4. fn read_username(path: &str) -> Result<String, io::Error> {
5. let username_file_result = fs::File::open(path);
7. let mut username_file = match username_file_result {
8. Ok(file) => file,
9. Err(e) => return Err(e),
10. };
12. let mut username = String::new();
14. match username_file.read_to_string(&mut username) {
15. Ok(_) => Ok(username),
16. Err(e) => Err(e),
17. }
18. }
20. fn main() {
21. //fs::write("config.dat", "alice").unwrap();
22. let username = read_username("config.dat");
23. println!("username or error: {username:?}");
24. }
Key points:
- The
usernamevariable can be eitherOk(string)orErr(error). - Use the
fs::writecall to test out the different scenarios: no file, empty file, file with username.
