Providing a Default: unwrap_or
Part of the Logic & Flow section of Coddy's Rust journey — lesson 40 of 66.
While .unwrap() and .expect() can extract values from an Option, they both have a major flaw: they panic when encountering a None. For safer code, Rust provides .unwrap_or() - a method that never panics.
The .unwrap_or() method takes a default value as an argument. If the Option contains a Some, it returns the inner value. If it's a None, it returns the default value you provided:
let maybe_score = Some(85);
let score = maybe_score.unwrap_or(0);
println!("Score: {}", score); // Prints: Score: 85
let no_score: Option = None;
let default_score = no_score.unwrap_or(0);
println!("Score: {}", default_score); // Prints: Score: 0This approach is much safer than .unwrap() because your program will never crash - you always get a usable value back.
Challenge
EasyYou will receive two inputs. The first input is a score (as a number), and the second input indicates whether the score is available (yes) or missing (no). Create an Option<i32> based on the availability status. Use .unwrap_or() to safely extract the score with a default value of 50, then print the final score.
Requirements:
- Read the first input (score) and trim whitespace
- Parse the first input to
i32 - Read the second input (availability status) and trim whitespace
- Create an
Option<i32>variable:- If the availability status is
yes, assignSome(score) - If the availability status is
no, assignNone
- If the availability status is
- Use
.unwrap_or(50)to extract the score with a default value of50 - Print the final score in the format:
Final score: [score]
Input:
- First line: A number representing the score (e.g.,
85) - Second line: Either
yesorno
Output:
- If the availability status is
yes:Final score: [score](the actual score) - If the availability status is
no:Final score: 50(the default value)
Cheat sheet
The .unwrap_or() method provides a safe way to extract values from an Option without panicking. It takes a default value as an argument and returns either the inner value if Some, or the default value if None:
let maybe_score = Some(85);
let score = maybe_score.unwrap_or(0);
// score is 85
let no_score: Option<i32> = None;
let default_score = no_score.unwrap_or(0);
// default_score is 0This method is safer than .unwrap() or .expect() because it never causes a panic - you always receive a usable value.
Try it yourself
use std::io;
fn main() {
// Read the score
let mut score_input = String::new();
io::stdin().read_line(&mut score_input).expect("Failed to read line");
let score: i32 = score_input.trim().parse().expect("Invalid number");
// Read the availability status
let mut availability = String::new();
io::stdin().read_line(&mut availability).expect("Failed to read line");
let availability = availability.trim();
// TODO: Write your code below
// Create an Option<i32> based on availability status
// Use .unwrap_or(50) to get the final score
// Print the result
println!("Final score: {}", final_score);
}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