Rest Patterns Ignore Middle Elements
Ignore middle elements with rest patterns: .. binds prefixes, suffixes, or both ends, and match dispatches unknown-length slices by shape.
Code
fn main() {
let scores = [91, 78, 85, 62, 99];
// .. swallows any number of middle elements: prefixes and suffixes both bind
let [top, second, ..] = scores;
println!("top: {top}, second: {second}");
let [.., second_last, last] = scores;
println!("second last: {second_last}, last: {last}");
let [first, .., final_score] = scores;
println!("first: {first}, final: {final_score}");
// A tuple's middle span is absorbed by .. the same way
let point = (3, 7, 11, 15);
let (x, .., w) = point;
println!("x: {x}, w: {w}");
// Slices of unknown length: rest patterns let match dispatch by shape
for data in [vec![5], vec![1, 2, 3], vec![]] {
match data.as_slice() {
[only] => println!("single: {only}"),
[first, .., last] => println!("from {first} to {last}"),
[] => println!("empty"),
}
}
}How it works
The snippet is organized around the function main.
Repetition is confined to for data in [vec![5], vec![1, 2, 3], vec![]] — the rest of the file is straight-line. Pattern matching via match forces each shape of the value to be handled.
What to watch for
- No external surface: all behavior comes from the standard library.
Applying it
Entry signature: fn main()
The demo output is labeled (top:, second last:, first:), so every printed line maps back to its originating operation.
Statements that matter
match data.as_slice() {
[only] => println!("single: {only}"),
[first, .., last] => println!("from {first} to {last}"),
[] => println!("empty"),
}
Interactive Tools for This Topic
Diff Ignoring WhitespaceCompare two blocks of text line by line and separate true differences from lines that differ only in spacing, indentation, or line endings.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.OpenAPI Endpoint ExplorerExplore OpenAPI 3.x YAML and JSON specifications locally with searchable endpoint tables, parameter summaries, security info, and cURL templates.
FAQ
- What does Rest Patterns Ignore Middle Elements print when run?
- Running the file directly is enough — expect labeled output lines such as `top:`, `second last:`, `first:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.