Hacker News new | ask | show | jobs
by Measter 2225 days ago
The way recoverable errors are signalled in Rust is through the return value, which is done using the `Result` enum. That enum is basically[0] defined like this:

    enum Result<T, E> {
        Ok(T),
        Err(E),
    }
Opening a file can, of course, fail for whatever reason, so `File::open` returns a `Result`. The `expect` method in that example is one defined on `Result` which takes that result and a message string, and if it's the `Ok` variant will return the value stored that variant. If its the `Err` variant it will print the input string and start an unrecoverable [1] panic, ending the program.

You would typically use `expect` (or `unwrap`, which does the same thing but without a custom message) when you either know for certain that it can't fail, or the failure condition is not something the program can recover from.

[0] Full definition can be found at https://doc.rust-lang.org/std/result/enum.Result.html

[1] Technically, you can catch a panic unwind [2], but it's more awkward and intended more for FFI boundaries than normal code. There's also no guarantee that the program will unwind. The compiler might have been set to abort on a panic instead of unwinding, in which case there's no unwind to catch.

[2] https://doc.rust-lang.org/std/panic/fn.catch_unwind.html