std-method

Result::unwrap / expect / unwrap_err / expect_err

Extract the branch expected by the program; the opposite branch panics. Prefer explicit handling for ordinary failures. The error-extraction forms are useful in negative tests. Expected stdout (not executed): invalid Common mistake: Using unwrap on unvalidated user input.

Formal Syntax & Structure

rust syntaxrust
fn unwrap(self) -> T where E: std::fmt::Debug; fn expect(self, msg: &str) -> T where E: std::fmt::Debug; fn unwrap_err(self) -> E where T: std::fmt::Debug; fn expect_err(self, msg: &str) -> E where T: std::fmt::Debug

Working Example

Example Snippetrust
fn main() {    let rejected: Result<i32, &str> = Err("invalid");    println!("{}", rejected.expect_err("invalid input should fail"));}
Rust Reference