0
0
Rustprogramming~15 mins

Matching multiple patterns in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Matching Multiple Patterns in Rust
📖 Scenario: You are building a simple program that categorizes animals based on their names. Some animals belong to groups that share common traits. You want to use Rust's match statement to check if an animal belongs to one of these groups by matching multiple patterns.
🎯 Goal: Create a Rust program that uses match with multiple patterns to print the group an animal belongs to.
📋 What You'll Learn
Create a variable called animal with the exact value "dog".
Create a variable called domestic_animals with the exact value ["dog", "cat", "rabbit"].
Use a match statement on the variable animal with multiple patterns combined using | to match domestic animals.
Print the exact output "dog is a domestic animal" when animal is "dog".
💡 Why This Matters
🌍 Real World
Matching multiple patterns is useful when you want to check if a value belongs to a group of options, like categorizing animals, handling commands, or processing user input.
💼 Career
Understanding pattern matching in Rust is important for writing clear and efficient code in system programming, web backend development, and other Rust applications.
Progress0 / 4 steps
1
Create the animal variable
Create a variable called animal and set it to the string "dog".
Rust
Hint

Use let animal = "dog"; to create the variable.

2
Create the domestic_animals array
Add a variable called domestic_animals and set it to the array ["dog", "cat", "rabbit"].
Rust
Hint

Use let domestic_animals = ["dog", "cat", "rabbit"]; to create the array.

3
Use match with multiple patterns
Use a match statement on animal with multiple patterns combined using | to match "dog", "cat", or "rabbit". For these cases, print "{} is a domestic animal" using animal in println!. For all other cases, print "{} is a wild animal" using animal in println!.
Rust
Hint

Use match animal { "dog" | "cat" | "rabbit" => ... , _ => ... } to match multiple patterns.

4
Print the result
Run the program and print the output. The output should be exactly "dog is a domestic animal".
Rust
Hint

Run the program to see the output.