5

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
  • 326,504
  • 69
  • 892
  • 1,159
Count Zero
  • 395
  • 2
  • 13
  • 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

6

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
  • 7,846
  • 1
  • 42
  • 56