Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match with vector element in Rust?

Tags:

match

rust

In Rust, matching a value like this works:

let x = 1;

match x {
    1 => println!("one"),
    2 => println!("two"),
    _ => println!("something else")
}

But using values from a vector instead of hard-coded numbers in match doesn't work:

let x = 1;
let list = vec![1, 2];

match x {
    list[0] => println!("one"),
    list[1] => println!("two"),
    _ => println!("something else")
}

This fails with the message:

error: expected one of `=>`, `@`, `if`, or `|`, found `[`
 --> src/main.rs:6:9
  |
6 |     list[0] => println!("one"),
  |         ^ expected one of `=>`, `@`, `if`, or `|` here

Why doesn't it work?

like image 221
Ananth Pattabiraman Avatar asked Jan 15 '19 12:01

Ananth Pattabiraman


People also ask

How do you use vector in Rust?

Using the get() method The second way of accessing the vector elements is to use the get(index) method with the index of a vector is passed as an argument. It returns the value of type Option<&t>. let v = vec!['

How does match work in Rust?

Rust has an extremely powerful control flow construct called match that allows you to compare a value against a series of patterns and then execute code based on which pattern matches.

How do you initialize VEC in Rust?

In Rust, there are several ways to initialize a vector. In order to initialize a vector via the new() method call, we use the double colon operator: let mut vec = Vec::new();

How do you clear a vector in Rust?

To remove all elements from a vector in Rust, use . retain() method to keep all elements the do not match. let mut v = vec![


1 Answers

The pattern of a match arm is defined as

Syntax
Pattern :
     LiteralPattern
   | IdentifierPattern
   | WildcardPattern
   | RangePattern
   | ReferencePattern
   | StructPattern
   | TupleStructPattern
   | TuplePattern
   | GroupedPattern
   | SlicePattern
   | PathPattern
   | MacroInvocation

It's either constant (including literal) or structural, not computed. A value defined as list[0] matches none of those definitions.

Fortunately, a match arm may also contain a guard expression, which allows for this:

let x = 1;
let list = vec![1, 2];

match x {
    _ if x == list[0] => println!("one"),
    _ if x == list[1] => println!("two"),
    _ => println!("something else")
}

Using if else would be cleaner, though (or a different structure if you have more cases, like a map, or the index).

like image 79
Denys Séguret Avatar answered Sep 21 '22 11:09

Denys Séguret