Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I avoid syntax repitition when matching enums?

I have a struct in which one of the fields is an enum, and when using a match statement there is a lot of repetition that feels avoidable.

Basically what I have now is

match self.foo // which is an enum, Foo {
    Foo::Bar => something,
    Foo::Bazz => something else,
    _ => you get the point

}

I tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

match self.foo {
    Foo::{
       Bar => something,
       Bazz => something else,
    }
}

but did not have the intended effect. Is it possible to not have to retype Foo:: every time or is it just something I need to live with?

>Solution :

You can import the names of enum variants to use them directly:

use Foo::*;
match self.foo {
    Bar => something,
    Bazz => something else,
}

This is how None and Some work without needing Option:: before them.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading