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 = 20;
match temp {
30..=50 => println!("Hot"),
10..=29 => println!("Warm"),
_ => println!("Cold"),
}In this example, a temperature of 20 would match the 10..=29 range and print "Warm". The range 30..=50 includes both 30 and 50, so temperatures of exactly 30 or 50 would both result in "Hot".
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"
Cheat sheet
Range patterns in match expressions allow you to match against a continuous span of values using the start..=end syntax, where ..= creates an inclusive range (both start and end values are included).
let score = 85;
match score {
90..=100 => println!("Grade: A"),
80..=89 => println!("Grade: B"),
70..=79 => println!("Grade: C"),
60..=69 => println!("Grade: D"),
_ => println!("Grade: F"),
}In this example, a score of 85 matches the 80..=89 range and prints "Grade: B". The range 90..=100 includes both 90 and 100.
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