Matching Ranges
Part of the Logic & Flow section of Coddy's Rust journey — lesson 3 of 66.
When you need to check if a value falls within a certain range of numbers, writing separate arms for each individual value would be tedious. Rust's match expression supports range patterns that let you match against a continuous span of values using the start..=end syntax.
The ..= operator creates an inclusive range, meaning both the start and end values are included in the match. Here's how you can use ranges in match arms:
let temp = 22;
match temp {
..=0 => println!("Freezing"),
1..=15 => println!("Cold"),
_ => println!("Warm"),
}In this example, a temperature of 22 would not match the first two ranges, so it falls through to the wildcard arm and prints "Warm". The range 1..=15 includes both 1 and 15, so any temperature from 1 to 15 would print "Cold".
Challenge
EasyYou will receive an age as input. Read the input, convert it to an integer, and use a match expression with range patterns to print the appropriate age category.
Requirements:
- If the age is
0..=12, print"Child" - If the age is
13..=19, print"Teenager" - If the age is
20..=64, print"Adult" - If the age is
65..=120, print"Senior" - For any other age, print
"Invalid age"
Input: A single integer representing the age
Output: Print the age category: "Child", "Teenager", "Adult", "Senior", or "Invalid age"
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 age: i32 = input.trim().parse().expect("Please enter a valid number");
// TODO: Write your code below using a match expression with range patterns
// Print the result
}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