A series (hopefully) where I geek out on Rust to anyone willing to hear. This time ✨Pattern Matching✨.

Pattern Matching is a powerful feature in Rust that allows you to check and retrieve data from data types that disclose their variant type. What makes Pattern Matching even more impressive is how Rust guarantees exhaustiveness in match expressions.

Now, let’s take the classic example of Fibonacci to illustrate how this works. The Fibonacci sequence is a sequence of numbers where the next number is found by adding up the two numbers before it. In the example, we’re using the match keyword to do pattern matching on the input n. If n is 0, we return 0. If n is 1, we return 1. For any other value, we call fibonacci(n) recursively for n-1 and n-2, and return the sum.

Pattern matching not only simplifies the code but also improves readability. The Rust compiler makes sure that all possible cases are covered, providing a fail-safe environment for pattern matching. It allows you to write more safe, concise, and readable code.

fn fibbonacci(n: u32) -> u32 {
    match n {
        0 => 0,
        1 => 1,
        _ => fibbonacci(n - 1) + fibbonacci(n - 2),
    }
}

We can see that we used the _ sign to signal to the compiler that we don’t actually care what data is in that arm. This is useful when we want to match on only a few cases and ignore the rest. We could further shorten the code by merging the first two arms into one using a pipe | to match on either 0 or 1:

fn fibbonacci(n: u32) -> u32 {
    match n {
        0|1 => n,
        _ => fibbonacci(n - 1) + fibbonacci(n - 2),
    }
}

Until next time.