15.5 Practical Examples

Seeing how Result handling appears in everyday code helps illustrate these principles in action.

15.5.1 Reading Files with Error Handling

use std::fs::File;
use std::io::{self, Read};

fn read_file(path: &str) -> Result<String, io::Error> {
    let mut contents = String::new();
    File::open(path)?.read_to_string(&mut contents)?;
    Ok(contents)
}

fn main() {
    match read_file("config.txt") {
        Ok(text) => println!("File contents:\n{}", text),
        Err(e) => eprintln!("Error reading file: {}", e),
    }
}

Any I/O error is propagated to the caller, which decides how to handle or report it.