Pattern Matching With Slice Patterns

Decompose slices with pattern matching and guards so list shapes like empty, single, and rest are handled without index gymnastics.

RustData Integrity

Code

rustsnippet
28 lines
fn describe(values: &[i32]) -> String {
    match values {
        // 切片模式:直接按形状解构
        [] => String::from("empty"),
        [single] => format!("single: {single}"),
        [first, second] => format!("pair: {first},{second}"),
        [first, .., last] => format!("range: {first}..{last} ({} items)", values.len()),
    }
}

fn classify(numbers: &[i32]) -> &'static str {
    match numbers {
        // 守卫条件:模式 + if
        [a, b] if a == b => "equal pair",
        [a, b] if a < b => "ascending pair",
        [a, b] => "descending pair",
        _ => "other",
    }
}

fn main() {
    for input in [vec![], vec![1], vec![1, 2], vec![1, 2, 3, 4]] {
        println!("{}", describe(&input));
    }
    for pair in [[3, 3], [1, 9], [9, 1]] {
        println!("{:?} -> {}", pair, classify(&pair));
    }
}

How the snippet works

Pattern Matching With Slice Patterns keeps everything in the functions describe, classify and main.

Iteration happens inside for input in [vec![], vec![1], vec![1, 2], vec![1, 2, 3, 4]] — everything outside it runs once. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

Applying it

Entry signature: fn describe(values: &[i32]) -> String

main is the driver: it invokes describe and classify before returning.

Statements that matter

fn classify(numbers: &[i32]) -> &'static str {
match numbers {
// 守卫条件:模式 + if
[a, b] if a == b => "equal pair",
[a, b] if a < b => "ascending pair",
[a, b] => "descending pair",
_ => "other",
}
}
fn describe(values: &[i32]) -> String {
match values {
// 切片模式:直接按形状解构
[] => String::from("empty"),
[single] => format!("single: {single}"),
[first, second] => format!("pair: {first},{second}"),
[first, .., last] => format!("range: {first}..{last} ({} items)", values.len()),
}
}

Interactive Tools for This Topic

FAQ

How do you run Pattern Matching With Slice Patterns?
This is a complete program, not a library excerpt — execution starts at the top.