Linux Format

EXPECT AND UNWRAP

-

Both expect() and unwrap() are used with the Result and Option data types and allow you to deal with error and unexpected conditions. Put simply, they allow you to get the value from a Result or Option variable, if it exists, or deal with the error condition the way you want to. The generic format of a Result value is

<&a_value, Error> , which means that we can either get Ok(&a_value) if it exists or get an Err(Error) value whereas the generic format of an Option value is

Option<&a_value> , which means that we either get a valid value Some(&a_value) or None . Bear in mind that Some is a data constructo­r. You can learn more about Option and Some by visiting https://doc.rust-lang.org/std/option/ enum.Option.html.

Having a Result value returned by a function named get_result() , we can extract its data as follows: match get_result() {

Ok(v) => println!("{}”, v),

Err(e) => println!{"get_result() error: {}”, e},

}

Similarly, having an Option value returned by a function named get_ option() , we can extract its data as follows: match get_option() { Some(v) => println!("{}”, v), None => println!("get_option(): No value!"),

}

Both presented cases are easy to understand, but require you to write some extra code. This is where unwrap() and expect() come into play. The expect() call is similar to unwrap() in the sense that they both panic your program. However, expect() allows you to set a custom panic error message. In practice, this means that if you want to avoid panicking and handle an error condition the way you want, you should use a match block instead. Last, if you want to panic from inside a match block, you can replace println!() with panic!() . All these and many more are illustrate­d in expect.rs. Running expect.rs generates the following output:

$ ./expect a_value: 123 get_result() error: This is an error message. x: 123 thread ‘main’ panicked at ‘get_result() invalid input: “This is an error message.“’, expect.rs:31:26

Use a RUST_BACKTRACE=1 environmen­t variable to display a backtrace.

Newspapers in English

Newspapers from Australia