In order to program in a more structured way, we'll use the try! macro, which will propagate the error upwards, causing an early return from the function, or unpack the success value. When returning the result, it needs to be wrapped in either Ok to indicate success or Err to indicate failure. This is shown here:
// code from Chapter 11/code/read_file_try.rs: use std::path::Path; use std::fs::File; use std::io::prelude::*; use std::error::Error; use std::io; fn main() { let path = Path::new("hello.txt"); let display = path.display(); let content = match read_file(path) { Err(why) => panic!("error reading {}: {}", display, Error::description(&why)), Ok(content) => content }; println!("{}", content); } fn read_file(path: &Path) -> Result<String, io::Error> {
let mut file = try!(File::open(path));
let mut buf = String::new();
try!(file.read_to_string(&mut buf));
Ok(buf)
}
This prints out:
"Hello Rust World!"