0
0
Rustprogramming~20 mins

Match guards in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Match Guards in Rust
📖 Scenario: You are building a simple program that categorizes numbers based on their value. You want to use Rust's match statement with match guards to check extra conditions.
🎯 Goal: Create a Rust program that uses match with match guards to print different messages depending on whether a number is positive, negative, or zero, and if it is even or odd.
📋 What You'll Learn
Create a variable called number with the value 7.
Create a variable called threshold with the value 0.
Use a match statement on number with match guards to check if the number is greater than, less than, or equal to threshold, and whether it is even or odd.
Print the correct message for each case.
💡 Why This Matters
🌍 Real World
Match guards help you handle different cases with extra conditions, useful in input validation, parsing, and decision-making in programs.
💼 Career
Understanding match guards is important for Rust developers to write clear and efficient code that handles complex conditions safely.
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
Create the threshold variable
Add a variable called threshold and set it to 0 below the number variable.
Rust
Hint

Use let threshold = 0; to create the variable.

3
Use match with match guards
Write a match statement on number using match guards to check these cases:
- If number is greater than threshold and even,
- If number is greater than threshold and odd,
- If number is less than threshold,
- If number is equal to threshold.
Inside each arm, assign a string message describing the case to a variable called message.
Rust
Hint

Use match number { n if condition => ... } to add match guards.

4
Print the message
Add a println! statement to print the message variable.
Rust
Hint

Use println!("{}", message); to print the message.