Slice patterns

Minimum Rust version: 1.26

Have you ever tried to pattern match on the contents and structure of a slice?Rust 2018 will let you do just that.

For example, say we want to accept a list of names and respond to that with agreeting. With slice patterns, we can do that easy as pie with:

  1. fn main() {
  2. greet(&[]);
  3. // output: Bummer, there's no one here :(
  4. greet(&["Alan"]);
  5. // output: Hey, there Alan! You seem to be alone.
  6. greet(&["Joan", "Hugh"]);
  7. // output: Hello, Joan and Hugh. Nice to see you are at least 2!
  8. greet(&["John", "Peter", "Stewart"]);
  9. // output: Hey everyone, we seem to be 3 here today.
  10. }
  11. fn greet(people: &[&str]) {
  12. match people {
  13. [] => println!("Bummer, there's no one here :("),
  14. [only_one] => println!("Hey, there {}! You seem to be alone.", only_one),
  15. [first, second] => println!(
  16. "Hello, {} and {}. Nice to see you are at least 2!",
  17. first, second
  18. ),
  19. _ => println!("Hey everyone, we seem to be {} here today.", people.len()),
  20. }
  21. }

Now, you don't have to check the length first.

We can also match on arrays like so:

  1. #![allow(unused_variables)]
  2. fn main() {
  3. let arr = [1, 2, 3];
  4. assert_eq!("ends with 3", match arr {
  5. [_, _, 3] => "ends with 3",
  6. [a, b, c] => "ends with something else",
  7. });
  8. }

More details

Exhaustive patterns

In the first example, note in particular the => … pattern.Since we are matching on a slice, it could be of any length, so we need a"catch all pattern" to handle it. If we forgot the => … oridentifier => … pattern, we would instead get an error saying:

  1. error[E0004]: non-exhaustive patterns: `&[_, _, _]` not covered

If we added a case for a slice of size 3 we would instead get:

  1. error[E0004]: non-exhaustive patterns: `&[_, _, _, _]` not covered

and so on…

Arrays and exact lengths

In the second example above, since arrays in Rust are of known lengths,we have to match on exactly three elements.If we try to match on 2 or 4 elements,we get the errors:

  1. error[E0527]: pattern requires 2 elements but array has 3

and

  1. error[E0527]: pattern requires 4 elements but array has 3

In the pipeline

When it comes to slice patterns, more advanced forms are planned buthave not been stabilized yet. To learn more, follow the tracking issue.