How to propagate errors

Propagate errors in Rust by returning Result types and using the ? operator to automatically pass failures up the call stack.

Propagate errors in Rust by returning a Result type and using the ? operator to short-circuit on failure. This automatically unwraps Ok values and returns Err values up the call stack.

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