9

I have an enum:

enum T {
    A(String),
}

I want to match a variable of this enum, but this code doesn't work:

match t {
    T::A("a") => println!("a"),
    T::A("b") => println!("b"),
    _ => println!("something else"),
}

I understand that I can do this, but it is so verbose in my opinion:

match t {
    T::A(value) => match value.as_ref() {
        "a" => println!("a"),
        "b" => println!("b"),
        _ => println!("something else"),
    },
}

Is there a shorter way to do this?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Count Zero
  • 495
  • 6
  • 15
  • You can also "transform" your problem by creating a parallel enum that has a `&str` instead of a `String`, but most people don't like that solution. – Shepmaster Mar 02 '18 at 19:00

1 Answers1

9

The only other way I think would be to use a match guard, but this is about as verbose as your version with nested matches.

match t {
    T::A(ref value) if value == "a" => println!("a"),
    T::A(ref value) if value == "b" => println!("b"),
    _ => println!("something else"),
}
dtolnay
  • 9,621
  • 5
  • 41
  • 62