Rust iter
Created By: chatGPT
In Rust, iterators are a powerful concept that allows you to traverse collections without the need for manual indexing. The iterator trait provides a way to work with sequences of items in a more functional style. Let's explore how to create and use iterators in Rust.
let numbers = vec![1, 2, 3, 4, 5];
let mut iter = numbers.iter();
To get the next item from the iterator, you can use the next() method. This method returns an Option type which can be either Some(item) or None if the iterator has been exhausted.
if let Some(&number) = iter.next() {
println!("Current number: {}", number);
}
You can also use for loops to iterate over the elements in a more concise way. This is often the preferred method for iterating through collections.
for number in numbers.iter() {
println!("Number: {}", number);
}
Rust provides various combinator methods that you can use with iterators to manipulate and transform data. For example, the map() method allows you to apply a function to each element in the iterator.
let squared: Vec<i32> = numbers.iter().map(|&x| x * x).collect();
You can also use the filter() method to include only those elements that meet certain criteria. This is especially useful for working with large datasets.
let even_numbers: Vec<i32> = numbers.iter().filter(|&&x| x % 2 == 0).cloned().collect();
Finally, you can use collect() to convert an iterator back into a collection. This is commonly used after applying various iterator methods to gather the results into a new vector or any other collection type.
let result: Vec<i32> = numbers.iter().filter(|&&x| x > 2).map(|&x| x * 2).collect();