For an array of fixed size, how do I use pattern matching to check if all elements have a specific value? For example, the below code does not work. Is there an alternative?
#![allow(unused)]
// You can extend a String with some chars:
fn main() {
let arr: [u8; 5] = [0, 0, 0, 0, 0];
match arr {
[0; 5] => println!("All elements are zeroes"),
[1; 5] => println!("All elements are ones"),
_ => println!("Something else!")
}
}
Thanks. I am aware of these two options. What I am looking for is a flexible check where I can use match where I can check for equality of all the elements in the array as well as do pattern matching as well - in the same match/pattern (based on certain pattern(s) - for example the head or tail being some specific values).
There's no "all elements are the same" pattern. Both of the above options allow you to still use the original array and perform additional pattern matching on it.
#![allow(unused)]
// You can extend a String with some chars:
fn main() {
let arr: [u8; 5] = [0, 0, 0, 0, 0];
match arr {
[0, 0, 0, 0, 0] => println!("All elements are zeroes"),
[1, 1, 1, 1, 1] => println!("All elements are ones"),
_ => println!("Something else!")
}
}
Of course that's a bit unhandy if you have a larger number of elements than 5.