Introduction
The
skip
function in Rust is an iterator adapter that allows you to bypass a specified number of elements from the start of an iterator. This function is useful when you need to ignore a certain number of initial elements and continue processing the rest.
Syntax
iterator.skip(n)
The
skip
function takes a single argument
n
, which specifies the number of elements to skip.
Example Usage
Example 1: Skipping the First Three Elements
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let result: Vec<i32> = numbers.into_iter().skip(3).collect();
println!("{:?}", result); // Output: [4, 5, 6]
}
Example 2: Skipping Elements in a Range
fn main() {
let range = 1..10;
let result: Vec<i32> = range.skip(5).collect();
println!("{:?}", result); // Output: [6, 7, 8, 9]
}
Example 3: Skipping Elements in a String Vector
fn main() {
let words = vec!["one", "two", "three", "four", "five"];
let result: Vec<&str> = words.into_iter().skip(2).collect();
println!("{:?}", result); // Output: ["three", "four", "five"]
}
Example 4: Skipping Elements in a Filtered Iterator
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8];
let result: Vec<i32> = numbers.into_iter().filter(|&x| x % 2 == 0).skip(2).collect();
println!("{:?}", result); // Output: [6, 8]
}
Example 5: Skipping More Elements Than Available
fn main() {
let numbers = vec![1, 2, 3];
let result: Vec<i32> = numbers.into_iter().skip(5).collect();
println!("{:?}", result); // Output: []
}
Considerations
- If
skip
is called with a number greater than the length of the iterator, it will simply return an empty iterator.
See Also
- take - Limits the iterator to a specified number of elements.
- filter - Filters elements of an iterator based on a predicate.
- map - Transforms each element of an iterator using a function.