Menu
Coddy logo textTech

Matching Multiple Values

Part of the Logic & Flow section of Coddy's Rust journey — lesson 2 of 66.

Sometimes you need to match several different values that should all trigger the same code. Instead of writing separate arms for each value, Rust lets you combine multiple patterns in a single arm using the | (OR) operator.

Here's how you can match multiple values in one arm:

let month = 12;

match month {
    12 | 1 | 2 => println!("Winter"),
    3 | 4 | 5 => println!("Spring"),
    6 | 7 | 8 => println!("Summer"),
    9 | 10 | 11 => println!("Fall"),
    _ => println!("Invalid month"),
}

The | operator works like "OR" in English - if the value matches any of the patterns separated by |, that arm will execute. This makes your code much cleaner than having separate arms that all do the same thing.

challenge icon

Challenge

Easy

You will receive a day number (1-7) as input, representing a day of the week. Read the input, convert it to an integer, and use a match expression with the | operator to print whether it's a weekday or weekend.

Requirements:

  • If the day is 1, 2, 3, 4, or 5, print "Weekday"
  • If the day is 6 or 7, print "Weekend"
  • For any other number, print "Invalid day"

Input: A single integer representing the day number

Output: Print either "Weekday", "Weekend", or "Invalid day"

Cheat sheet

You can combine multiple patterns in a single match arm using the | (OR) operator. If the value matches any of the patterns separated by |, that arm will execute.

let month = 12;

match month {
    12 | 1 | 2 => println!("Winter"),
    3 | 4 | 5 => println!("Spring"),
    6 | 7 | 8 => println!("Summer"),
    9 | 10 | 11 => println!("Fall"),
    _ => println!("Invalid month"),
}

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 day: i32 = input.trim().parse().expect("Please enter a number");
    
    // TODO: Write your code below using match expression with | operator
    
}
quiz iconTest yourself

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

All lessons in Logic & Flow