Functional Error Handling Patterns in Rust

Handle recoverable errors with Result and the ? operator, and use panic! for unrecoverable failures in Rust.

Use Result<T, E> for recoverable errors and panic! for unrecoverable ones, propagating errors with the ? operator or handling them via match.

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

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

fn main() {
    match read_file("hello.txt") {
        Ok(contents) => println!("File contents: {}", contents),
        Err(e) => eprintln!("Error: {}", e),
    }
}