top | item 23207490

(no title)

aaronjanse | 5 years ago

> why am I expecting an error? Shouldn't that keyword be "on_exception" or something?

`expect` takes an input that is either an error or a value, then turns that input into just a value. The provided string is the error message if something goes wrong (i.e. the input was an error).

discuss

order

einpoklum|5 years ago

A little counter-intuitive IMHO. But - I live with C++'s template voodoo, so I guess I can't really complain.

Measter|5 years 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