0
0
Rustprogramming~5 mins

Using unwrap and expect in Rust

Choose your learning style9 modes available
Introduction

Sometimes, you have a value that might be missing or an error might happen. unwrap and expect help you get the value out quickly or stop the program with a message if something is wrong.

When you are sure a value exists and want to get it directly.
When you want to stop the program if a value is missing and see a clear error message.
When testing small pieces of code where handling errors is not needed.
When you want to quickly get a value from an option or result without writing extra code.
Syntax
Rust
let value = option.unwrap();
let value = result.expect("Error message if failed");

unwrap() stops the program if the value is missing or error happens.

expect() does the same but lets you add a custom error message.

Examples
This gets the number 5 from the option and prints it.
Rust
let some_option = Some(5);
let value = some_option.unwrap();
println!("Value is {}", value);
This will stop the program with a panic because the option is empty.
Rust
let none_option: Option<i32> = None;
let value = none_option.unwrap();
This stops the program and shows the message "Failed to get value" because the result is an error.
Rust
let result: Result<i32, &str> = Err("Oops");
let value = result.expect("Failed to get value");
Sample Program

This program shows how to use unwrap on an option and expect on a result to get values safely.

Rust
fn main() {
    let some_option = Some("hello");
    let value = some_option.unwrap();
    println!("Unwrapped value: {}", value);

    let result: Result<i32, &str> = Ok(10);
    let number = result.expect("Failed to get number");
    println!("Expected number: {}", number);
}
OutputSuccess
Important Notes

Using unwrap or expect is easy but can cause your program to stop if the value is missing.

Use them only when you are sure the value exists or during quick tests.

For safer code, handle errors with match or if let.

Summary

unwrap gets the value or stops the program if missing.

expect does the same but lets you add a custom error message.

Use them carefully to avoid unexpected crashes.