Rust Iterator
In Rust, an Iterator
is a trait that represents a sequence of values that can be iterated over using a for
loop or other methods. Rust's iterators provide a way to abstract over sequences of data and perform common operations on them.
Here's an example of how to use an iterator in Rust:
fn main() { let numbers = vec![1, 2, 3, 4, 5]; // iterate over the numbers and print them to the console for number in numbers.iter() { println!("{}", number); } // use the `map` method to create a new iterator with each value multiplied by 2 let doubled_numbers = numbers.iter().map(|&x| x * 2); // use the `collect` method to create a new vector from the iterator let doubled_numbers_vec: Vec<i32> = doubled_numbers.collect(); // print the new vector to the console println!("{:?}", doubled_numbers_vec); }
In this example, we're creating a vector of integers called numbers
and iterating over it using the iter
method to print each value to the console using a for
loop.
We're then using the map
method on the iterator to create a new iterator where each value is multiplied by 2 using a closure. We're then using the collect
method to create a new vector from the iterator.
Finally, we're printing the new vector to the console using the println!
macro.
Rust's iterators provide a wide range of methods for performing common operations on sequences of data, such as filter
, fold
, any
, all
, and more. Rust's iterators are also lazy, which means that they only compute values as they are needed, making them efficient and memory-safe.