What Is the Difference Between unwrap, expect, and the ? Operator?

Use unwrap for default panics, expect for custom panic messages, and the ? operator to propagate errors to the caller.

Use unwrap to panic with a default message, expect to panic with a custom message, and the ? operator to propagate errors to the caller.

fn main() {
    let file = std::fs::File::open("hello.txt")
        .expect("Failed to open file: custom message");
    
    let contents = std::fs::read_to_string(&file)?;
    
    let value: Option<i32> = Some(42);
    let num = value.unwrap();
}

The ? operator requires the function to return a Result or Option type to propagate the error or None value automatically.