Menu
Coddy logo textTech

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 icon

Challenge

Easy

You 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
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow