/*
In Rust, you can apply slice patterns directly to fixed-size arrays ([T; N]).
Because the size of a fixed array is known at compile time,
the Rust compiler enforces strict length checks,
ensuring your patterns match the array's exact dimensions
without requiring runtime length checks.
*/
/// Analyzes a fixed 4-element integer array using array and slice patterns.
pub fn analyze_quad(arr: [i32; 4]) -> String {
match arr {
// Pattern 1: Exact match for a specific sequence
[1, 2, 3, 4] => String::from("Exact sequence: 1-2-3-4"),
// Pattern 2: Match elements at specific positions, ignoring the middle two
[first, _, _, last] if first == last => {
format!("Bookend match: starts and ends with {}", first)
}
// Pattern 3: Match elements at the beginning, binding the remaining sub-slice
// `rest` becomes a slice `&[i32]` of length 2.
[0, rest @ ..] => {
format!("Starts with zero, remaining elements: {:?}", rest)
}
// Pattern 4: Match with a middle rest pattern (e.g., first and last known)
[first, .., last] => {
format!("General quad: first={}, last={}", first, last)
}
}
}
fn main() {
// Example 1: Exact sequence match
let exact = [1, 2, 3, 4];
println!("{}", analyze_quad(exact));
// Example 2: Bookend match (first and last elements are equal)
let bookend = [7, 9, 2, 7];
println!("{}", analyze_quad(bookend));
// Example 3: Leading element match with rest binding (`rest @ ..`)
let zero_start = [0, 42, 99, 5];
println!("{}", analyze_quad(zero_start));
// Example 4: Catch-all via `[first, .., last]`
let standard = [5, 10, 15, 20];
println!("{}", analyze_quad(standard));
}
/*
run:
Exact sequence: 1-2-3-4
Bookend match: starts and ends with 7
Starts with zero, remaining elements: [42, 99, 5]
General quad: first=5, last=20
*/