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

pub enum Foo {
  A(i32),
  B(String)
}

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.

#![feature(let_else)]

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

Playground.

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

4 Likes

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.