0
0
Rustprogramming~20 mins

Match expression deep dive in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Match expression deep dive
📖 Scenario: You are building a simple program that categorizes numbers into groups using Rust's match expression. This helps you understand how to use match to check different conditions and handle multiple cases clearly.
🎯 Goal: Learn how to use Rust's match expression to categorize numbers into named groups and print the category.
📋 What You'll Learn
Create a variable called number with the value 7.
Create a variable called category that uses a match expression on number.
Use match arms to categorize number as "small" if it is 1, 2, or 3.
Use match arms to categorize number as "medium" if it is 4, 5, or 6.
Use a catch-all _ arm to categorize any other number as "large".
Print the category variable.
💡 Why This Matters
🌍 Real World
Using <code>match</code> expressions helps you write clear and safe code that handles many possible cases, like checking user input or categorizing data.
💼 Career
Understanding <code>match</code> is essential for Rust programming jobs, especially in systems programming, embedded devices, and safe code development.
Progress0 / 4 steps
1
Create the number variable
Create a variable called number and set it to 7.
Rust
Hint

Use let number = 7; to create the variable.

2
Set up the match expression
Add a variable called category that uses a match expression on number.
Rust
Hint

Start with let category = match number { _ => "unknown" }; to set up the match.

3
Add arms for small and medium numbers
In the match expression for category, add arms to return "small" if number is 1, 2, or 3, and "medium" if number is 4, 5, or 6.
Rust
Hint

Use the | symbol to match multiple values in one arm, like 1 | 2 | 3 => "small".

4
Add catch-all arm and print the category
Change the catch-all arm to return "large" for any other number. Then print the category variable using println!.
Rust
Hint

Use _ => "large" for the catch-all arm and println!("{}", category); to print.