Take And Skip Slice Iteration Windows
Cut iteration windows with take and skip: take grabs the first n items, skip drops them, and combining both yields offset paging over a slice.
Code
fn main() {
let scores = vec![42, 17, 93, 58, 7, 66, 25, 80];
// take(n): grabs only the first n items; overruns past the length are silently ignored
let head: Vec<i32> = scores.iter().copied().take(3).collect();
println!("head: {head:?}");
// skip(n) drops the first n: combined with take it forms an offset-paged window
let page2: Vec<i32> = scores.iter().copied().skip(3).take(3).collect();
println!("page2: {page2:?}");
// Skipping past the length yields an empty iterator
let none: Vec<i32> = scores.iter().copied().skip(99).collect();
println!("over skip: {none:?}");
// skip_while/take_while cut by predicate: drop leading non-matches, then take the consecutive run
let above50: Vec<i32> = scores
.iter()
.copied()
.skip_while(|s| *s <= 50)
.take_while(|s| *s > 50)
.collect();
println!("run above 50: {above50:?}");
}How the snippet works
Take And Skip Slice Iteration Windows is built around the function main.
Applying it
The demo output is labeled (head:, page2:, over skip:), so every printed line maps back to its originating operation.
Statements that matter
let page2: Vec<i32> = scores.iter().copied().skip(3).take(3).collect();
let head: Vec<i32> = scores.iter().copied().take(3).collect();
let none: Vec<i32> = scores.iter().copied().skip(99).collect();
FAQ
- What does Take And Skip Slice Iteration Windows print when run?
- Run it as a complete program — the output lines carry labels such as `head:`, `page2:`, `over skip:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.