Let Foo::A(y) = x; // or panic

pub enum Foo {

Foo x;

let Foo::A(y) = x; // does not compile

let y = match x {
  Foo::A(y) => y,
  _ => panic!(),

Is there a concise way to say: match this arm of the enum ... or panic ?

Context: parsing some json / yaml / tree like "untyped" data into Rust structs; so I know before hand "in a valid file, we must take arm A here".

Looks like a case for let-else.


fn f(x: Foo) {
    let Foo::A(y) = x else { panic!() };


On stable, an Option returning method for the variant + unwrap would do the trick.


I'm on stable, so the suggestion is to pay the one time cost of writing:

impl Foo {
  get_A(&self) -> Option<i32> { ... }
  get_B(&self) -> Option<String> { ... }


Something like that, yeah.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.