Slice Patterns For Array Destructuring
Destructure slices in match arms: fixed-length patterns assert exact element counts, and head with rest @ .. binds the remaining items as a subslice.
Code
fn describe(readings: &[i32]) -> String {
match readings {
[] => "empty".to_string(),
// 固定长度模式:只匹配恰好一个 / 两个元素的切片
[only] => format!("single: {only}"),
[first, second] => format!("pair: {first} vs {second}"),
// head/tail 拆分:rest @ .. 把剩余元素绑定为子切片
[head, rest @ ..] => format!("head {head}, {} more: {rest:?}", rest.len()),
}
}
fn main() {
let data = [7, 11, 13, 17];
println!("{}", describe(&data));
println!("{}", describe(&data[..2]));
println!("{}", describe(&data[..1]));
println!("{}", describe(&[]));
// let 解构固定长度数组:.. 吞掉剩余元素
let [a, b, ..] = data;
println!("first two: {a} {b}");
}Inside the snippet
Slice Patterns For Array Destructuring comes down to the functions describe and main.
Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.
Using it
Entry signature: fn describe(readings: &[i32]) -> String
Running the file prints labeled results such as first two: — each operation’s effect is visible in the output.
The sequence describe lives in main; running the file triggers it.
Key statements
match readings {
[] => "empty".to_string(),
// 固定长度模式:只匹配恰好一个 / 两个元素的切片
[only] => format!("single: {only}"),
[first, second] => format!("pair: {first} vs {second}"),
// head/tail 拆分:rest @ .. 把剩余元素绑定为子切片
[head, rest @ ..] => format!("head {head}, {} more: {rest:?}", rest.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
- What does Slice Patterns For Array Destructuring print when run?
- Execute the whole file; each printed line is prefixed with a label like `first two:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.