The expect
Part of the Logic & Flow section of Coddy's Rust journey — lesson 39 of 66.
While .unwrap() gets the job done, it has a major drawback: when it panics on a None, the error message is generic and unhelpful. This is where .expect() comes to the rescue.
The .expect() method works exactly like .unwrap() - it extracts the value from a Some and panics on a None. The key difference is that .expect() lets you provide a custom panic message:
let maybe_score = Some(95);
let score = maybe_score.expect("Score should always be present");
println!("Your score is: {}", score);If the Option contains a Some, .expect() returns the inner value just like .unwrap(). But if it's a None, instead of a generic panic message, you'll see your custom message, making it much easier to understand what went wrong and where.
Challenge
EasyYou will receive two inputs. The first input is a product name, and the second input indicates whether the product is in stock (yes) or out of stock (no). Create an Option<String> that contains Some(product_name) if the product is in stock, or None if it's out of stock. Use .expect() with a descriptive message to extract the product name and print it.
Requirements:
- Read the first input (product name) and trim whitespace
- Read the second input (stock status) and trim whitespace
- Create an
Option<String>variable:- If the stock status is
yes, assignSome(product_name.to_string()) - If the stock status is
no, assignNone
- If the stock status is
- Use
.expect()with the message"Product should be in stock"to extract the product name - Print the extracted product name in the format:
Product available: [product_name]
Input:
- First line: A product name (e.g.,
Laptop) - Second line: Either
yesorno
Output:
- If the stock status is
yes:Product available: [product_name] - If the stock status is
no: The program will panic with the custom message "Product should be in stock" (this is expected behavior for this challenge)
Note: When the stock status is no, calling .expect() on None will cause a panic with your custom message. This demonstrates how .expect() provides more helpful error information compared to .unwrap().
Cheat sheet
The .expect() method works like .unwrap() but allows you to provide a custom panic message for better error debugging.
When called on an Option:
- If it contains
Some, it returns the inner value - If it contains
None, it panics with your custom message
let maybe_score = Some(95);
let score = maybe_score.expect("Score should always be present");
println!("Your score is: {}", score);The custom error message makes it easier to identify what went wrong and where in your code.
Try it yourself
use std::io;
fn main() {
// Read product name
let mut product_name = String::new();
io::stdin().read_line(&mut product_name).expect("Failed to read line");
let product_name = product_name.trim();
// Read stock status
let mut stock_status = String::new();
io::stdin().read_line(&mut stock_status).expect("Failed to read line");
let stock_status = stock_status.trim();
// TODO: Write your code below
// Create an Option<String> based on stock_status
// Use .expect() to extract the product name
// Print the result in the format: Product available: [product_name]
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
The 'match' ExpressionMatching Multiple ValuesMatching RangesThe 'if let' ExpressionLoops as ExpressionsRecap - Simple Command Parser4Grouping Data with Structs
What is a Struct?Structs OverviewAccessing Struct FieldsMutable StructsStructs as Function ParametersTuple StructsRecap - Create a Book Struct7Handling Errors with 'Result'
What is a 'Result'?Using 'match' with 'Result'is_ok() and is_err()Shortcuts: unwrap and expectThe Question Mark Operator '?'Parsing Strings to NumbersRecap - Safe Division Function10Closures & Anonymous Functions
What is a Closure?Defining a Simple ClosureClosures with ParametersCapturing the EnvironmentRecap - Simple Adder Closure2Introduction to Vectors
What is a Vector?Creating a VectorAdding Elements with pushAccessing Vector ElementsIterating Over a VectorMutable IterationRemoving ElementsRecap - Basic Score Tracker5Key-Value Pairs with Hash Maps
What is a Hash Map?Creating a Hash MapInserting Key-Value PairsAccessing ValuesIterating Over a Hash MapUpdating a ValueRemoving a PairRecap - Word Counter8Project: Simple Item Inventory
Project SetupAdding an ItemChecking StockSelling an ItemPutting it all together6Handling Absence with 'Option'
What is an 'Option'?Using 'match' with 'Option'is_some() and is_none()Unwrapping an 'Option'The expectProviding a Default: unwrap_orRecap - Find an Element