How to Use the ? Operator in Rust

The `?` operator in Rust simplifies error handling by automatically propagating errors from `Result` or `Option` types to the caller.

The ? operator in Rust is a shorthand for error propagation that automatically returns the error from a function if a Result or Option is Err or None, otherwise it unwraps the value. It simplifies nested match statements by allowing you to chain operations that might fail without writing explicit error handling logic at every step.

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

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

The function read_file returns a Result type, and the ? operator handles the Err cases for File::open and read_to_string by immediately returning the error to the caller.