Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Rust Iterators

Rust Iterators

Iterators (Iterator) in Rust are a powerful and flexible tool for step-by-step access and manipulation of collections (such as arrays, vectors, linked lists, etc.).

Rust's iterators are lazily evaluated, meaning the iterator itself does not perform operations immediately; it produces values only when you need them.

Iterators allow you to traverse sequences in a declarative way, such as elements of collection types like arrays, slices, and linked lists.

The core idea behind iterators is to separate the data processing flow from the data itself, making code clearer, more readable, and more maintainable.

In Rust, iterators are defined by implementing the Iterator trait.

The most basic trait method is next, which returns the next element in the iterator one by one until None is returned to indicate the end.

Example

pub

trait

Iterator

{

   

type

Item

;

   

   

fn

next

(

&

mut

self

)

->

Option

<

Self

::

Item

;

   

   

// Other default-implemented methods such as map, filter, etc.

}

Iterators follow these principles:


Create iterators

The most common way is through a collection's .iter()、.iter_mut() or .into_iter() method to create an iterator:

Create a borrowing iterator using the iter() method:



let vec = vec![1, 2, 3, 4, 5];

let iter = vec.iter();

Create a mutable borrowing iterator using the iter_mut() method:



let mut vec = vec![1, 2, 3, 4, 5];

let iter_mut = vec.iter_mut();

Create an owning iterator using the into_iter() method:



let vec = vec![1, 2, 3, 4, 5];

let into_iter = vec.into_iter();

Example

let

v

=

vec

!

[

1

,

2

,

3

]

;

let

mut

iter

=

v.iter

(

)

;

assert_eq

!

(

iter.next

(

)

,

Some

(

&

1

)

)

;

assert_eq

!

(

iter.next

(

)

,

Some

(

&

2

)

)

;

assert_eq

!

(

iter.next

(

)

,

Some

(

&

3

)

)

;

assert_eq

!

(

iter.next

(

)

,

None

)

;

 

// End of iteration

Iterator methods

Rust's iterators provide a rich set of methods for processing elements in a collection; some common methods include:

Transform each element using the map() method:



let vec = vec![1, 2, 3, 4, 5];

let squared_vec: Vec = vec.iter().map(|x| x * x).collect();

Filter elements by condition using the filter() method:



let vec = vec![1, 2, 3, 4, 5];

let filtered_vec: Vec = vec.into_iter().filter(|&x| x % 2 == 0).collect();

Iterating over an iterator with a for loop

Rust provides for loop syntax to traverse elements in an iterator, which is a more concise and intuitive way of iteration.

Under the hood, Rust's for loops actually use iterators.



let vec = vec![1, 2, 3, 4, 5];

for &num in vec.iter() {

    println!("{}", num);

}

In this loop, vec.iter() returns an iterator; the for loop traverses this iterator, assigning each element to the num variable, then executes the code in the loop body.

Consuming adapters

Use an iterator until it is fully consumed.

Iterators have many methods that consume the iterator; they return a final result (such as a sum, collection, etc.) by performing iteration, and these methods consume the iterator itself.

Example

let

v

=

vec

!

[

1

,

2

,

3

]

;

let

sum

:

i32

=

v.iter

(

)

.sum

(

)

;

assert_eq

!

(

sum

,

6

)

;

Adapter

Iterator adapters allow you to change or filter an iterator's contents through method chaining without consuming it immediately.

let v = vec![1, 2, 3, 4, 5];

let doubled: Vec = v.iter().map(|x| x * 2).collect();

assert_eq!(doubled, vec![2, 4, 6, 8, 10]);

Iterator chaining

Multiple iterator adapters can be chained together to form an iterator chain.

Example

use

std

::

iter

::

Peekable

;

let

arr

=

[

1

,

2

,

3

,

4

,

5

]

;

let

mut

iter

=

arr.into_iter

(

)

.peekable

(

)

;

while

let

Some

(

val

)

=

iter.next

(

)

{

   

if

val

%

2

==

0

{

       

continue

;

   

}

    println

!

(

"{}"

,

val

)

;

}

Collectors

Use the collect method to gather an iterator's elements into some kind of collection.

let arr = [1, 2, 3, 4, 5];

let sum: i32 = arr.into_iter().sum();

Lazy evaluation

As mentioned earlier, Rust iterators are lazy, meaning that methods like map() and filter() do not execute immediately; data is only actually processed when a consuming method like collect() is called. This makes iterator processing more efficient by avoiding unnecessary computation.

Custom iterators

You can also implement the Iterator trait for your own types; you only need to define the next() method.

For example, implement a simple iterator from 1 to 5:

Example

struct

Counter

{

    count

:

usize

,

}

impl

Counter

{

   

fn

new

(

)

->

Counter

{

       

Counter

{

count

:

0

}

   

}

}

impl

Iterator

for

Counter

{

   

type

Item

=

usize

;

   

   

fn

next

(

&

mut

self

)

->

Option

<

Self

::

Item

{

       

self

.count

+=

1

;

       

if

self

.count

<=

5

{

            Some

(

self

.count

)

       

}

else

{

            None

       

}

   

}

}

let

mut

counter

=

Counter

::

new

(

)

;

while

let

Some

(

num

)

=

counter.next

(

)

{

    println

!

(

"{}"

,

num

)

;

 

// Output 1 to 5

}

Parallel iterators

If you need to parallelize operations in a multithreaded environment, the rayon crate supports parallel iterators; by using .par_iter() instead of .iter(), you can speed up iteration in a multithreaded environment.

Iterators and lifetimes

An iterator's lifetime is tied to the lifetime of the elements it iterates over. An iterator can borrow elements or take ownership of them. This is controlled in the iterator's implementation via lifetime parameters.

Iterators and closures

Iterator adapters are often used together with closures, which allow you to provide custom logic for iterator operations.

Iterators and performance

Iterators are usually very efficient because they allow the compiler to make optimizations. For example, the compiler can inline calls to iterator adapters and can exploit the lazy evaluation nature of iterators.

Example

The following example demonstrates how to use an iterator to traverse an array and output its elements.

Example

// Main function

fn

main

(

)

{

   

// Define an array of integers

   

let

numbers

=

vec

!

[

1

,

2

,

3

,

4

,

5

]

;

   

// Traverse the array using an iterator and output each element

    println

!

(

"Iterating through the array:"

)

;

   

for

num

in

numbers.iter

(

)

{

        println

!

(

"{}"

,

num

)

;

   

}

   

// Use the iterator's map method to square each element and collect the results into a new array

   

let

squared_numbers

:

Vec

<

i32

=

numbers.iter

(

)

.map

(

|

x

|

x

x

)

.collect

(

)

;

   

// Output the squared array

    println

!

(

"Squared numbers: {:?}"

,

squared_numbers

)

;

}

In the code above, we first defined an array of integers numbers, then use iter() method to get the array's iterator, and through for loop to traverse the iterator, outputting each element. Next, using the iterator's map() method to square each element, and using collect() method to collect the results into a new array squared_numbers . Finally, the squared array is output.

Running this program, you can see each element of the original array output, as well as the new array after squaring:

Iterating through the array:

1

2

3

4

5

Squared numbers: [1, 4, 9, 16, 25]

This example demonstrates the basic usage of iterators in Rust, including traversal, transformation, and collecting results.

The following example uses the filter() method to filter an array and outputs the filtered result:

Example

// Main function

fn

main

(

)

{

   

// Define an array of integers

   

let

numbers

=

vec

!

[

1

,

2

,

3

,

4

,

5

,

6

,

7

,

8

,

9

,

10

]

;

   

// Use the iterator's filter method to filter the array, selecting even numbers

   

let

even_numbers

:

Vec

<

i32

=

numbers.iter

(

)

.filter

(

|&

x

|

x

%

2

==

0

)

.cloned

(

)

.collect

(

)

;

   

// Output the filtered result

    println

!

(

"Even numbers: {:?}"

,

even_numbers

)

;

}

In the code above, we first defined an array of integers numbers, then using the iterator's filter() method to filter the array, selecting the even numbers. In the filter() method's closure, we use the modulo operation to determine whether an element is even. Finally, using the cloned() method to clone each even value, and using collect() method to collect the results into a new array even_numbers into it. Finally, the filtered result is output.

Running this program, you can see all even numbers in the array output:

Even numbers: [2, 4, 6, 8, 10]

This example demonstrates the usage of the filter() method in Rust iterators, and how to combine it with other methods to filter arrays.

Rust iterator methods

The following are some commonly used iterator methods in Rust, along with brief descriptions and examples:

Method Names Description Example
next() Return the next element in the iterator. let mut iter = (1..5).into_iter(); while let Some(val) = iter.next() { println!("{}", val); }
size_hint() Return lower and upper bounds on the number of remaining elements in the iterator. let iter = (1..10).into_iter(); println!("{:?}", iter.size_hint());
count() Count the number of elements in the iterator. let count = (1..10).into_iter().count();
nth() Return the nth element in the iterator. let third = (0..10).into_iter().nth(2);
last() Return the last element in the iterator. let last = (1..5).into_iter().last();
all() Return true if all elements in the iterator satisfy a condition, true。 let all_positive = (1..=5).into_iter().all(\|x\| x > 0);
any() Return true if at least one element in the iterator satisfies a condition, true。 let any_negative = (1..5).into_iter().any(\|x\| x < 0);
find() Return the first element in the iterator that satisfies a condition. let first_even = (1..10).into_iter().find(\|x\| x % 2 == 0);
find_map() Apply a function to the elements of the iterator, returning the first one for which the function returns Some 's result. let first_letter = "hello".chars().find_map(\|c\| if c.is_alphabetic() { Some(c) } else { None });
map() Apply a function to each element in the iterator. let squares: Vec = (1..5).into_iter().map(\|x\| x * x).collect();
filter() Retain elements in the iterator that satisfy a condition. let evens: Vec = (1..10).into_iter().filter(\|x\| x % 2 == 0).collect();
filter_map() Apply a function to the elements of the iterator; if the function returns Some, keep the result. let chars: Vec = "hello".chars().filter_map(\|c\| if c.is_alphabetic() { Some(c.to_ascii_uppercase()) } else { None }).collect();
map_while() Apply a function to the elements of the iterator until the function returns None。 let first_three = (1..).into_iter().map_while(\|x\| if x <= 3 { Some(x) } else { None });
take_while() Take elements from the iterator while they satisfy a condition, until one does not. let first_five = (1..10).into_iter().take_while(\|x\| x <= 5).collect::>()
skip_while() Skip elements in the iterator while they satisfy a condition, until one does not. let odds: Vec = (1..10).into_iter().skip_while(\|x\| x % 2 == 0).collect();
for_each() Perform an operation on each element in the iterator. let mut counter = 0; (1..5).into_iter().for_each(\|x\| counter += x);
fold() Fold the elements of the iterator using an accumulator. let sum: i32 = (1..5).into_iter().fold(0, \|acc, x\| acc + x);
try_fold() Fold the elements of the iterator, possibly returning early upon encountering an error. let result: Result = (1..5).into_iter().try_fold(0, \|acc, x\| if x == 3 { Err("Found the number 3") } else { Ok(acc + x) });
scan() Perform a stateful fold over the elements of the iterator. let sum: Vec = (1..5).into_iter().scan(0, \|acc, x\| { *acc += x; Some(*acc) }).collect();
take() Take at most n elements from the iterator. let first_five = (1..10).into_iter().take(5).collect::>()
skip() Skip the first n elements of the iterator. let after_five = (1..10).into_iter().skip(5).collect::>()
zip() Pack elements from two iterators into tuples. let zipped = (1..3).zip(&['a', 'b', 'c']).collect::>()
cycle() Repeat an iterator's elements indefinitely. let repeated = (1..3).into_iter().cycle().take(7).collect::>()
chain() Chain multiple iterators together. let combined = (1..3).chain(4..6).collect::>()
rev() Reverse the order of elements in an iterator. let reversed = (1..4).into_iter().rev().collect::>()
enumerate() Add an index to each element in the iterator. let enumerated = (1..4).into_iter().enumerate().collect::>()
peeking_take_while() Take elements satisfying a condition while preserving the iterator's state so you can continue taking subsequent elements. let (first, rest) = (1..10).into_iter().peeking_take_while(\|&x\| x < 5);
step_by() Return elements of the iterator with a specified step. let even_numbers = (0..10).into_iter().step_by(2).collect::>()
fuse() Create an additional iterator that can still be called after the iterator is exhausted next() method. let mut iter = (1..5).into_iter().fuse(); while iter.next().is_some() {}
inspect() Execute a closure when taking each element, without changing the element. let mut counter = 0; (1..5).into_iter().inspect(\|x\| println!("Inspecting: {}", x)).for_each(\|x\| println!("Processing: {}", x));
same_items() Compare whether two iterators produce the same sequence of elements. let equal = (1..5).into_iter().same_items((1..5).into_iter());

Summary

Rust's iterators are a powerful and flexible tool that allows sequences to be processed in a declarative way. Designed with safety, performance, and expressiveness in mind, iterators are one of the core features of the Rust language. Through iterators, Rust programmers can write code that is both safe and efficient.