DEV Community

Roman
Roman

Posted on

Compact `match` in Rust

match often used to work with enums, let's look at this example:

enum NextStep {
    TurnLeft,
    TurnRight
}

fn main() {
    let next_step = NextStep::TurnLeft;
    match next_step {
        NextStep::TurnLeft => println!("turn left"),
        NextStep::TurnRight => println!("turn right"),
    }
}
Enter fullscreen mode Exit fullscreen mode

It may not be obvious, but enums in Rust can be brought into the current namespace, allowing for more compact code:

// ...
    use NextStep::*;
    match next_step {
        TurnLeft => println!("turn left"),
        TurnRight => println!("turn right"),
    }
// ...
Enter fullscreen mode Exit fullscreen mode

And, to limit the effect to just match, you will have to set boundaries using {} for an additional scope:

// ...
    {
        use NextStep::*;
        match next_step {
            // ...
        }
    }
// ...
Enter fullscreen mode Exit fullscreen mode

My links

I'm making my perfect todo, note-taking app Heaplist, you can try it here heaplist.app
And I have a twitter @rsk

Top comments (0)