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.
Code
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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Pattern Matching With Slice Patterns?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.