is_some() and is_none()
Part of the Logic & Flow section of Coddy's Rust journey — lesson 37 of 66.
Sometimes you need to check whether an Option contains a value without actually extracting that value. Rust provides two convenient methods for this: .is_some() and .is_none().
Both methods return a boolean value, making them perfect for use in if conditions:
let maybe_score = Some(85);
if maybe_score.is_some() {
println!("We have a score!");
}
if maybe_score.is_none() {
println!("No score available");
}The .is_some() method returns true if the Option contains a Some value, and false if it's None. The .is_none() method works in the opposite way - it returns true for None and false for Some.
Challenge
EasyYou will receive a number as input. Create an Option<i32> that contains Some(number) if the number is positive, or None if the number is zero or negative. Use .is_some() and .is_none() to check the Option and print the appropriate message.
Requirements:
- Read the input and convert it to
i32 - Create an
Option<i32>variable:- If the number is positive (greater than 0), assign
Some(number) - If the number is zero or negative, assign
None
- If the number is positive (greater than 0), assign
- Use
.is_some()to check if theOptioncontains a value - If
.is_some()returnstrue, print:Positive number detected - Use
.is_none()to check if theOptionis empty - If
.is_none()returnstrue, print:No positive number
Input:
- A single integer (e.g.,
42,0, or-5)
Output:
- If the number is positive:
Positive number detected - If the number is zero or negative:
No positive number
Cheat sheet
Use .is_some() to check if an Option contains a value:
let maybe_score = Some(85);
if maybe_score.is_some() {
println!("We have a score!");
}Use .is_none() to check if an Option is empty:
if maybe_score.is_none() {
println!("No score available");
}Both methods return boolean values (true or false).
Try it yourself
use std::io;
fn main() {
// Read input
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
let number: i32 = input.trim().parse().expect("Invalid input");
// TODO: Write your code below
// Create an Option<i32> based on whether the number is positive
// Check if the Option is Some and print the appropriate message
}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