HiveBrain v1.2.0
Get Started
← Back to all entries
principlerustMajor

When should we use unwrap vs expect in Rust

Submitted by: @import:stackoverflow-api··
0
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:
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 "unwrap with a message", and that is expect.

  • expect == unwrap with a message



  • expect_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.

Context

Stack Overflow Q#61301581, score: 77

Revisions (0)

No revisions yet.