How to Use Result<T, E> in Rust

The Complete Guide

Use Result<T, E> to return success or error values and handle them with match or the ? operator.

Use Result<T, E> to return either a success value of type T or an error of type E from functions that might fail. Handle the result using match to explicitly deal with both success and error cases, or use ? to propagate errors up the call stack.

use std::fs::File;

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

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