Pattern match - same elements array

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!")
    }
}

Just use ordinary equality: Playground.

Alternatively, write a helper function.

1 Like

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.

For that you can use a match that checks specific patterns, and then uses variable name patterns with an if condition, like this.

You can also match against a named constant:

  const ONES: [i32; 5] = [1; 5];

  match [0; 5] {
    ONES => dbg!("ones"),
    _ => dbg!("something else")
  };

There are also inline const patterns but they’re unstable as of now.

9 Likes

Okay. Got it. Thanks.

As I understand there is no way to use [0; 5] without an if condition in match. It would be really nice to have such a syntax for array match pattern.

Just for completeness. This works as well.

#![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.

5 Likes

Yes, yes. This works perfectly, but you are right. If I have too many values in the array, it gets clumsy. That's why I felt, a syntax like

match arr {
    [0; 32] => println!("All elements are zero"),
    ... 
}

will be so nice. Thoughts @nikomatsakis ??

There is an unstable feature:

#![feature(inline_const_pat)]

fn main() {
    let arr: [u8; 5] = [0, 0, 0, 0, 0];
    match arr {
        const { [0; 5] } => println!("All elements are zeroes"),
        const { [1; 5] } => println!("All elements are ones"),
        _ => println!("Something else!")
    }
}
7 Likes

I don't think pinging Niko for something like this is going to be productive (or polite).

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.