#Match multiple enum pattern contained in a Vec<T>

8 messages · Page 1 of 1 (latest)

undone portal
#

I want to achieve something like I'm doing with the | syntax.

enum Foo {
  Something,
  SomethingElse,
  Whatever,
}

fn bar(x: Foo) {
  let valids = vec![Something, SomethingElse];

  match x {
    Something | SomethingElse => println!("Something..."),
    _ => println!("Whatever"),
  }
}

But the multiple pattern I want to match against are defined in a Vec<Foo> which is known at compile time, I don't want to have duplicates declarations.

fn bar(x: Foo, valids: Vec<Foo>) {
  match x {
    /* Enum type inside valids */ => println!("Valid"),
    _ => println!("Not valid"),
  }
}

Is it possible ?

dry thistle
#

The only ways to abstract in a pattern are
(1) a constant, which can only match one value not a set
(2) a macro

#

you can define a macro so that valids!() => println!("Valid") works

#

(the macro must produce the exact patterns/consts; it still can't refer to data)

spiral tide
#

if valids.contains(x) ?

undone portal
#

I'm already using valids.contains(x) but I want to benefit from the compiler optimizations using match. I thought of doing a macro but I was wondering if something like this already exists.

dry thistle
#

it can't, because there's no way to abstract "match one of N items" away from the syntax

undone portal
#

Good to know, thanks !