🤖💻🤔 Rust Match Expressions

Switch Case on Steroids! 🚀🔥

If you’re a programmer, you know that control flow statements are the backbone of any programming language. They allow you to make decisions based on certain conditions and execute different pieces of code accordingly. One such statement is the switch case statement, which allows you to match a value against a series of patterns and execute the corresponding code block.

Rust takes this concept to the next level with its match expression, which is like switch case on steroids! 💪

🤔 What are match expressions?

Match expressions in Rust allow you to match a value against a series of patterns and execute the corresponding code block. These patterns can be anything from simple values to complex structures. The match expression then evaluates the value and matches it against the first pattern that matches, executing the corresponding code block.

Here’s a simple example:

1
2
3
4
5
6
let x = 1;
match x {
    1 => println!("One"),
    2 => println!("Two"),
    _ => println!("Anything else"),
}

In this example, we’re matching the value of x against three patterns. If x is equal to 1, we’ll print “One”. If x is equal to 2, we’ll print “Two”. And if x doesn’t match any of those patterns, we’ll print “Anything else”.

👨‍💻 How are match expressions different from switch case?

Match expressions in Rust are more powerful than switch case in several ways:

  1. Exhaustive matching: Unlike switch case, match expressions require you to handle all possible cases. This means that if you forget to handle a particular case, Rust will give you a compile-time error.
  2. Pattern matching: With match expressions, you can match against more than just simple values. You can match against complex structures like tuples and enums, and even use guards to add additional conditions to your matches.
  3. Variable binding: Match expressions also allow you to bind variables to parts of the matched value, which can be very useful in certain situations.

Here’s an example of pattern matching with a tuple:

1
2
3
4
5
6
let tup = (0, 2);
match tup {
    (0, x) => println!("x is {}", x),
    (y, 2) => println!("y is {}", y),
    _ => println!("Anything else"),
}

In this example, we’re matching the tuple against two patterns. If the first element is 0, we’ll bind the second element to the variable x and print its value. If the second element is 2, we’ll bind the first element to the variable y and print its value. And if the tuple doesn’t match either of those patterns, we’ll print “Anything else”.

crust example 🦀🔨

🔥 Let’s take a look at how match expressions in Rust can be used to handle built-in commands in a shell! 🐚

In this example, we have my Rust-based shell crust. The execute_builtin function uses a match expression to match the input argument against the builtin field, which is an enum representing various built-in commands.

👨‍💻 Here’s the code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#[derive(Clone, Debug, PartialEq, Default)]
pub enum Builtins {
    #[default]
    None,
    Exit,
    CD,
    Echo,
    Alias,
}

pub fn execute_builtin(input: &Input) {
    match input.builtin {
        Builtins::Exit => exit(0),
        Builtins::Echo => println! {"{}", input.args.join(" ")},
        Builtins::Alias => { /* TODO use hash map to define aliases */ }
        Builtins::CD => change_dir(input),
        _ => {}
    }
}

🔎 As you can see, if the input matches a specific command, the corresponding action is executed. For example, if the input’s built-in command is Builtins::Exit, the program will exit with a status code of 0. Similarly, if the built-in command is Builtins::Echo, the input’s arguments are printed to the console. If the built-in command is Builtins::CD, the shell will change its working directory to the path specified in the input. Finally, if none of the built-in commands match, the program does nothing.

🚀 Conclusion

Match expressions in Rust are a powerful and flexible way to handle control flow. They allow you to match against a wide range of patterns and provide compile-time safety by requiring exhaustive matching. If you’re coming from another language that uses switch case statements, you’ll find that Rust’s match expressions are like switch case on steroids! So give them a try and see how they can simplify and improve your code. 🔥

Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy