How to use slice patterns in a slice of a dynamic-size array in Rust

1 Answer

0 votes
/*
In Rust, slicing a dynamically sized collection (like a Vec<T>, a dynamic array, 
or a sub-slice) allows you to use slice patterns at runtime.
*/

/// Analyzes a dynamic slice of integers (`&[i32]`) using runtime slice patterns.
pub fn analyze_dynamic_slice(slice: &[i32]) -> String {
    match slice {
        // Pattern 1: Matches an empty slice (length 0)
        [] => String::from("The slice is empty."),

        // Pattern 2: Matches a slice with exactly one element
        [x] => format!("Single element slice: {}", x),

        // Pattern 3: Matches a slice with exactly two elements
        [first, second] => format!("Two elements: first = {}, second = {}", first, second),

        // Pattern 4: Matches a slice starting with 0 and ending with 9, 
        // capturing all intermediate values into a sub-slice `middle` using `@`.
        [0, middle @ .., 9] => {
            format!("Bounded slice (starts with 0, ends with 9). Middle elements: {:?}", middle)
        }

        // Pattern 5: Matches a slice starting with 42, capturing everything else into `rest`.
        [42, rest @ ..] => {
            format!("Special prefix (42). Remaining elements: {:?}", rest)
        }

        // Pattern 6: General catch-all for any other slice of length 3 or more,
        // capturing the first and last elements while ignoring or bridging the rest.
        [first, .., last] => {
            format!("General slice (length >= 3). First = {}, Last = {}", first, last)
        }
    }
}

fn main() {
    // Example 1: Empty slice
    let empty: &[i32] = &[];
    println!("{}", analyze_dynamic_slice(empty));

    // Example 2: Single element slice from a vector
    let vec_data = vec![7];
    println!("{}", analyze_dynamic_slice(&vec_data));

    // Example 3: Two-element slice
    let pair = &[10, 20];
    println!("{}", analyze_dynamic_slice(pair));

    // Example 4: Bounded slice matching pattern with `middle @ ..`
    let bounded = &[0, 4, 5, 6, 9];
    println!("{}", analyze_dynamic_slice(bounded));

    // Example 5: Specific prefix matching with `rest @ ..`
    let custom = &[42, 100, 200, 300];
    println!("{}", analyze_dynamic_slice(custom));

    // Example 6: General catch-all slice
    let general = &[5, 12, 18, 25];
    println!("{}", analyze_dynamic_slice(general));
}


/*
run:

The slice is empty.
Single element slice: 7
Two elements: first = 10, second = 20
Bounded slice (starts with 0, ends with 9). Middle elements: [4, 5, 6]
Special prefix (42). Remaining elements: [100, 200, 300]
General slice (length >= 3). First = 5, Last = 25

*/

 



answered 1 day ago by avibootz
...