Enum expect type syntax sugar

I often find myself writen code that looks like this:

enum A {
    A1(B),
    A2(i8),
}
enum B {
    B1(String),
    B2(i16),
}
fn main()  {
    let mut a = A::A1(B::B1("test".to_string()));
    
    match a {
        A::A1(mut b) => {
            match b {
                B::B1(mut s) => s.push('c'),
                _ => panic!(),
            }
        }
        _ => panic!(),
    }
}

A very convenient shorthand would be to something like this:

a.expect_A1().expect_B1().push('c');

I could do that my writing a expect_A1 and expect_B1 method, but this would require manual labor and clutter the code.
Is there some way to conveniently shorten the syntax in the first example? Is it possible to dervie these excpect_Enumvariant functions?

match a {
    A::A1(B::B1(mut s)) => s.push('c'),
    _ => panic!(),
}
1 Like

This can put two matches together, but I need something to put matches and member calls together. I should have posted the more commen case:

match a {
    A::A1(val) => {
        val.method();
    }
    _ => panic!();
}

This would be a lot more cleaner if I could write it as

a.expect_A1().method()`

You could add such methods to your enum manually, or you could use a macro to generate them. The enum-as-inner crate has a #[derive] macro that almost does what you want, and might be a good starting point.

3 Likes

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.