I'm new to rust and trying to understand when should we use unwrap vs expect.
Here's a sample code:
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let query = args.get(1).unwrap();
println!("query from unwrawp: {}", query);
let query = args.get(1).expect("insufficient arguments");
println!("query from expect: {}", query);
//$ cargo run hello
//OUTPUT:
//query from expect: hello
//query from unwrawp: hello
}
Only difference I observed is there's a custom panic message in expect.
Are these two interchangeable or are there any special scenarios where we should use one over the other?
Rust doesn't have function overloading, so there should be a way to declare "unwrap
with a message", and that is expect
.
expect
== unwrap
with a messageexpect_err
== unwrap_err
with a messageAbout usage scenarios of "unwrap vs expect" Rust Book (Ch 9) says:
Using expect instead of unwrap and providing good error messages can convey your intent and make tracking down the source of a panic easier. Because this error message starts with the text we specified... it will be easier to find where in the code this error message is coming from.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With