Rust Pattern Matching Exercises with Solutions and Explanations
Rust Pattern Matching Exercises [14 exercises with solution and Explanation]
[An editor is available at the bottom of the page to write and execute the scripts. Go to the editor]
1. Write a Rust function that takes an integer and returns "even" if the integer is even and "odd" if it's odd.
2. Write a Rust function that takes a tuple (char, i32) and returns "Vowel" if the first element is a vowel ('a', 'e', 'i', 'o', 'u') and "Consonant" otherwise.
3. Write a Rust function that takes a Result
4. Write a Rust function that takes an Option
5. Write a Rust function that takes a vector and returns "Vector is empty!" if it's empty and "Vector is not empty!" otherwise.
6. Write a Rust function that takes a tuple (i32, i32) and returns "Equal" if both elements are equal, "Increasing" if the first element is less than the second, and "Decreasing" if the first element is greater than the second.
7. Write a Rust function that takes a slice of integers and returns "Ascending order!" if the integers are in ascending order, "Descending order!" if they are in descending order, and "Random" otherwise.
8. Write a Rust function that takes a string slice and returns "Uppercase characters!" if all characters are uppercase, "Lowercase characters!" if all characters are lowercase, and "Mixedcase characters!" otherwise.
9. Write a Rust function that takes a Result
10. Write a Rust function that takes a vector of tuples (i32, i32) and returns the sum of all the first elements if the second elements are all even, the sum of all the second elements if the first elements are all odd, and 0 otherwise.
11. Write a Rust function that takes an Option<&str> and returns the length of the string if it's Some(&str) and 0 if it's None.
12. Write a Rust function that takes a vector of booleans and returns "All true!" if all elements are true, "All false!" if all elements are false, and "Mixed!" otherwise.
13. Write a Rust function that takes a slice of integers and returns the sum of all elements if the sum is greater than 100, the product of all elements if the product is less than 100, and 0 otherwise.
14. Write a Rust function that takes a tuple (i32, i32, i32) and returns "Equilateral" if all sides are equal, "Isosceles" if two sides are equal, and "Scalene" otherwise.
Rust Code Editor:
More to Come !
Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/rust/functional-programming/pattern-matching.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics