Rust into iter ExampleCall the into_iter function to convert a collection into an iterator. This can help with return values.
Into 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.
Avoid errors. With into_iter() we can fix errors involving FromIterator. For example, if we want to have a u8, we need into_iter() to keep u8 instead of &u8.
Example code. 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.
Tip The iter() function will not work here, as it will have element references, not the original types.
Thus When returning from a function based on an iterator, we often need to use 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); }
Error info. If we try to use iter() in the return statement, we will get a FromIterator error. It is important to consider the element types.
And If we need the original element type, we should use into_iter() instead of iter().
Error output:
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...
A summary. 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).
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on 9/17/2022 (new).
© 2007-2022 sam allen.
see site info on the changelog.