principlerustMajor
When should we use unwrap vs expect in Rust
Viewed 0 times
unwrapshouldusewhenrustexpect
Problem
I'm new to rust and trying to understand when should we use unwrap vs expect.
Here's a sample code:
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?
Here's a sample code:
use std::env;
fn main() {
let args: Vec = env::args().collect();
let query = args.get(1).unwrap();
println!("query from unwrawp: {}", query);
let query = args.get(1).expect("the program should be called with a commandline argument");
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?
Solution
Rust doesn't have function overloading, so there should be a way to declare "
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.
unwrap with a message", and that is expect.expect==unwrapwith a message
expect_err==unwrap_errwith 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.
Context
Stack Overflow Q#61301581, score: 77
Revisions (0)
No revisions yet.