问题
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?
回答1:
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 message
About 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.
来源:https://stackoverflow.com/questions/61301581/when-should-we-use-unwrap-vs-expect-in-rust