How to Write Panic-Free Rust Code

Write panic-free Rust by using Result types and the ? operator to handle errors gracefully instead of crashing.

You write panic-free Rust code by replacing panic! with Result types to handle errors gracefully. Use the ? operator to propagate errors up the call stack instead of crashing the program.

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

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

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