iter
Suppose we wish get an iterator, and then return the result of the iterator. The into_iter
function is helpful here—it converts the collection into an iterator.
With into_iter()
we can fix errors involving FromIterator
. If we want u8
, we need into_iter()
to keep u8
instead of references to u8
values.
Consider this example code—the get_flattened_vec
function returns a Vector
of u8
. To do this, we must use into_iter()
and then call collect()
on that iterator.
iter()
function will not work here, as it will have element references, not the original types.into_iter()
not iter
.fn get_flattened_vec() -> Vec<u8> { // Create nested vectors. let vecs = vec![vec![], vec![]]; // Use into iter to convert to an iterator in place, then flatten and collect. vecs.into_iter().flatten().collect() } fn main() { let result = get_flattened_vec(); println!("{:?}", result); }[]
If we try to use iter()
in the return statement, we will get a FromIterator
error. It is important to consider the element types.
into_iter()
instead of iter()
.error[E0277]: a value of type Vec<u8> cannot be built from an iterator over elements of type &_ --> src/main.rs:5:27... = help: the trait FromIterator<&_> is not implemented for Vec<u8> = help: the trait FromIterator<T> is implemented for Vec<T> note: required by a bound in collect...
There is an important distinction between iter()
and into_iter()
in Rust. Iter will return references, while into_iter()
will return the original types (which are needed for returns).