Rust Function: Analyzing Boolean vector
Rust Pattern Maching: Exercise-12 with Solution
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.
Sample Solution:
Rust Code:
// Function that takes a vector of booleans and returns a message based on the elements.
fn check_bools(vector: Vec<bool>) -> &'static str {
// Check if the vector is empty
if vector.is_empty() {
// If empty, return "Empty vector!"
return "Empty vector!";
}
// Check if all elements are true
let all_true = vector.iter().all(|&x| x);
// Check if all elements are false
let all_false = vector.iter().all(|&x| !x);
// If all elements are true, return "All true!"
if all_true {
"All true!"
// If all elements are false, return "All false!"
} else if all_false {
"All false!"
// Otherwise, return "Mixed!"
} else {
"Mixed!"
}
}
fn main() {
// Example usage
let all_true = vec![true, true, true, true];
let all_false = vec![false, false, false, false];
let mixed = vec![true, false, true, true];
// Print the result for each vector
println!("{}", check_bools(all_true)); // Output: All true!
println!("{}", check_bools(all_false)); // Output: All false!
println!("{}", check_bools(mixed)); // Output: Mixed!
}
Output:
All true! All false! Mixed!
Explanation:
The above Rust code defines a function "check_bools()" that takes a vector of booleans and returns a message based on the elements. The function checks if all elements are true, all elements are false, or if there's a mix of true and false values. In the "main()" function, example vectors are provided and the result is printed for each vector.
Rust Code Editor:
Previous: Rust Function: Length of option string handling.
Next: Rust Function: Analyzing integer slice.
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://w3resource.com/rust/functional-programming/rust-pattern-matching-exercise-12.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics