DEV Community

Roman
Roman

Posted on

1

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay