15.5 Practical Examples

15.5.1 Reading Files with Error Handling

Scenario: Read the contents of a file, handling potential errors gracefully.

Example:

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),
    }
}