Rust Function: Compare Tuple elements
Rust Pattern Maching: Exercise-5 with Solution
Write a Rust function that takes a vector and returns "Vector is empty!" if it's empty and "Vector is not empty!" otherwise.
Sample Solution:
Rust Code:
// Function that checks if the input vector is empty or not and returns a corresponding string.
fn check_vector(vector: Vec<i32>) -> &'static str {
// Match on the length of the vector using the `is_empty()` method
match vector.is_empty() {
true => "Vector is empty!", // If vector is empty, return this message
false => "Vector is not empty!" // If vector is not empty, return this message
}
}
fn main() {
// Example usage
let empty_vector: Vec<i32> = vec![];
let non_empty_vector = vec![100, 200, 300, 400];
// Call the check_vector function with both empty and non-empty vectors
println!("{}", check_vector(empty_vector)); // Output: Vector is empty!
println!("{}", check_vector(non_empty_vector)); // Output: Vector is not empty!
}
Output:
Vector is empty! Vector is not empty!
Explanation:
In the exercise above,
- check_vector Function:
- This function takes a vector of integers (Vec<i32>) as input.
- Inside the function, a 'match' statement is used to pattern match on the result of the "is_empty()" method called on the vector.
- If the vector is empty (true branch of the match), the function returns the string "Vector is empty!".
- If the vector is not empty (false branch of the match), the function returns the string "Vector is not empty!".
- main Function:
- In the "main()" function, two vectors are created: one empty vector 'empty_vector' and one non-empty vector 'non_empty_vector'.
- The "check_vector()" function is called twice, once with 'empty_vector' and once with 'non_empty_vector'.
- The result of each call is printed to the console using "println!()".
Rust Code Editor:
Previous: Rust Function: Check Option Some or None.
Next: Rust Function: Compare Tuple elements.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://www.w3resource.com/rust/functional-programming/rust-pattern-matching-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics