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 = 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 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"

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