Day 12f: Advanced Array Patterns and Matching in Rust

Venkat Annangi
Venkat Annangi
08/10/2024 02:53 4 min read 50 views
#rust-arrays #rust #108 days of rust

Day 12f: Advanced Array Patterns and Matching in Rust

Introduction

Rust’s pattern matching system is one of its most powerful features, and it extends well to arrays. Arrays can be destructured and matched in a variety of ways, making your code more expressive. In this post, we will explore how to destructure arrays, perform advanced matching, use guards, and handle more complex cases involving arrays.

Destructuring Arrays

One of the simplest uses of pattern matching in arrays is destructuring. Destructuring allows you to extract individual elements from an array and bind them to variables, leaving the rest of the array behind or simply ignoring it. This can simplify code when you only need a few elements of the array.

fn main() {

    let arr = [10, 20, 30, 40];

    let [first, second, ..] = arr;

    println!("First: {}, Second: {}", first, second);  // Output: First: 10, Second: 20

}

Here, first and second are extracted from the array, and the rest is ignored. You can also combine this with more advanced patterns.

Full Destructuring

If you want to access all elements in the array, you can destructure them fully:

fn main() {

    let arr = [100, 200, 300];

    let [a, b, c] = arr;

    println!("a: {}, b: {}, c: {}", a, b, c);  // Output: a: 100, b: 200, c: 300

}

Full destructuring is useful when you know the size of the array and want to handle each element separately. Note that this works best with small arrays of fixed size.

Partial Destructuring with Wildcards

You can ignore parts of the array by using the wildcard pattern _. This is helpful when you only care about certain elements in an array.

fn main() {

    let arr = [5, 10, 15, 20];

    let [first, _, third, _] = arr;

    println!("First: {}, Third: {}", first, third);

}

Matching Arrays with Pattern Matching

Rust allows you to match specific patterns within an array, making your code concise and easy to follow when handling specific cases. For instance, you might want to take specific actions based on the length or content of an array.

fn check_array(arr: [i32; 4]) {

    match arr {

        [1, 2, ..] => println!("Starts with 1, 2"),

        [_, _, 3, 4] => println!("Ends with 3, 4"),

        _ => println!("Different pattern"),

    }

}



fn main() {

    let arr1 = [1, 2, 3, 4];

    let arr2 = [5, 6, 3, 4];

    check_array(arr1);  // Output: Starts with 1, 2

    check_array(arr2);  // Output: Ends with 3, 4

}

This is an example of how matching specific patterns in arrays can help identify different cases, like whether an array starts or ends with certain values.

Using Guards in Array Matching

Pattern guards allow you to add conditions to your matches. This is useful for adding extra logic to your matching criteria, such as checking if the sum of the first two elements exceeds a certain threshold.

fn main() {

    let arr = [30, 40, 50, 60];

    match arr {

        [x, y, ..] if x + y > 50 => println!("Sum of first two elements is greater than 50"),

        _ => println!("No match"),

    }

}

Guards allow for more complex conditions in pattern matching, offering flexibility in your code logic.

Matching Arrays of Different Lengths

You can use the match expression to handle arrays of different lengths. This allows you to respond to arrays dynamically without worrying about their size beforehand.

fn main() {

    let arr = [10, 20, 30, 40, 50];

    match arr {

        [x, y, z, ..] => println!("Starts with three elements: {}, {}, {}", x, y, z),

        [a, b] => println!("Starts with two elements: {}, {}", a, b),

        _ => println!("Array is of a different length"),

    }

}

This code shows how pattern matching can be used with variadic elements (using ..) to handle arrays of different lengths dynamically.

Conclusion

Pattern matching with arrays allows you to write more concise and expressive code. With destructuring, partial matching, and guards, you can handle array patterns cleanly and efficiently. Using pattern matching in combination with advanced guards provides a great toolset for dealing with arrays in Rust.

Comments