Shortcuts: unwrap and expect
Part of the Logic & Flow section of Coddy's Rust journey — lesson 45 of 66.
You've already learned about .unwrap() and .expect() with Option, and these same methods work with Result too. However, their behavior is slightly different when dealing with success and failure cases.
The .unwrap() method extracts the value from an Ok variant, but if the Result is an Err, your program will panic and crash. Similarly, .expect() does the same thing but allows you to provide a custom panic message that makes debugging easier:
let success: Result = Ok(42);
let value = success.expect("This should work!");
println!("Value: {}", value); // Prints: Value: 42
// This would panic with the custom message:
// let failure: Result = Err("Something went wrong");
// let value = failure.expect("This should work!"); // Panics!While these methods provide quick access to successful values, they should be used carefully. They're most appropriate when you're absolutely certain the operation will succeed, or during development and testing.
Challenge
EasyYou will receive two inputs. The first input is a number (as a string), and the second input is a status indicator (ok or error). Create a Result<i32, &'static str> based on the status. If the status is ok, create an Ok containing the parsed number. If the status is error, create an Err with the message "Invalid operation". Use .expect() with a custom message to extract the value from the Result and print it.
Requirements:
- Read the first input (number) and trim whitespace
- Parse the first input to
i32 - Read the second input (status) and trim whitespace
- Create a
Result<i32, &'static str>variable:- If the status is
ok, assignOk(parsed_number) - If the status is
error, assignErr("Invalid operation")
- If the status is
- Use
.expect("Failed to get value")to extract the value from theResult - Print the extracted value in the format:
Value: [value]
Input:
- First line: A number (e.g.,
75) - Second line: Either
okorerror
Output:
- If the status is
ok:Value: [number] - If the status is
error: The program will panic with the custom message (not tested in this challenge)
Note: For this challenge, test cases will only use the ok status to ensure successful execution. The error case would cause a panic, which is the expected behavior of .expect() when encountering an Err.
Cheat sheet
The .unwrap() and .expect() methods work with Result types to extract values from the Ok variant.
.unwrap() extracts the value from an Ok, but panics if the Result is an Err:
let success: Result<i32, &str> = Ok(42);
let value = success.unwrap();
println!("Value: {}", value); // Prints: Value: 42.expect() works the same way but allows you to provide a custom panic message for easier debugging:
let success: Result<i32, &str> = Ok(42);
let value = success.expect("This should work!");
println!("Value: {}", value); // Prints: Value: 42
// This would panic with the custom message:
let failure: Result<i32, &str> = Err("Something went wrong");
let value = failure.expect("This should work!"); // Panics with custom messageThese methods should be used carefully, as they will crash your program if the Result is an Err. They're most appropriate when you're certain the operation will succeed or during development and testing.
Try it yourself
use std::io;
fn main() {
// Read the first input (number)
let mut number_input = String::new();
io::stdin().read_line(&mut number_input).expect("Failed to read line");
let number_input = number_input.trim();
// Parse the number to i32
let parsed_number: i32 = number_input.parse().expect("Failed to parse number");
// Read the second input (status)
let mut status = String::new();
io::stdin().read_line(&mut status).expect("Failed to read line");
let status = status.trim();
// TODO: Write your code below
// Create a Result<i32, &'static str> based on the status
// Use .expect() to extract the value
// Print the result in the format: Value: [value]
}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 together