In Rust, an iterator is a pattern that allows you to perform some task on a sequence of items in turn. An iterator is responsible for the logic of iterating over each item and determining when the sequence has finished.
In Rust, iterators are created by methods called iter()
and into_iter()
on collections like Vec
, HashMap
, etc. Rust’s iterators have a method called next()
that returns Some(element)
when there are more elements, and None
when there are no more elements.
Here’s an example of basic usage of an iterator:
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);
In this example, v.iter()
returns an iterator over &i32
. The next
method returns the next value wrapped in Some
if there’s a value, or None
if it’s gone through every item already.
Rust’s iterators are lazy, meaning they have no effect until you consume them. One common way to consume an iterator is to use a for loop, which is internally implemented using iterators:
let v = vec![1, 2, 3];
for i in v.iter() {
println!("{}", i);
}
In addition to next
, the Iterator
trait defines a variety of useful methods (provided by the standard library), which can be used to do complex tasks. Here are a few examples:
map
: Transforms the elements of an iterator.filter
: Filters elements based on a condition.fold
: Accumulates a value across an iterator.collect
: Consumes the iterator and returns a collection.Here’s an example using map
and collect
:
let v = vec![1, 2, 3];
let v_squared: Vec<_> = v.iter().map(|x| x * x).collect();
assert_eq!(v_squared, vec![1, 4, 9]);
In this case, map
is used to square each element of the iterator, and collect
is used to consume the iterator and produce a new Vec
.
Note: iter()
gives you an iterator over &T
, and into_iter()
gives you an iterator over T
. There’s also iter_mut()
, which gives you an iterator over &mut T
, allowing you to modify the elements.
fn main() {
let v = vec!["Rust", "Programming", "Language"];
let mut it = v.iter();
println!("{:?}", it.next());
println!("{:?}", it.next());
println!("{:?}", it.next());
println!("{:?}", it.next());
let iter = v.iter();
for item in iter {
println!("{}", item);
}
/*
输出:
Some("Rust")
Some("Programming")
Some("Language")
None
Rust
Programming
Language
*/
/*
iter() 返回一个只读可重入迭代器,迭代器元素的类型为 &T,
into_iter() 返回一个只读不可重入迭代器,迭代器元素的类型为 T,
iter_mut() 返回一个可修改重入迭代器,迭代器元素的类型为 &mut T
*/
}