How to Use Result<T, E> for Error Handling in Rust

Use Result<T, E> to handle recoverable errors by returning Ok for success and Err for failure, allowing your program to continue running.

Use Result<T, E> to return either a success value of type T or an error of type E from functions that might fail. Return Ok(value) on success and Err(error) on failure, then handle the result using match or the ? operator to propagate errors.

use std::fs::File;
use std::io::Error;

fn read_file(path: &str) -> Result<String, 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 reading file: {}", e),
    }
}