Into Iter Moves Elements Through Adapters
into_iter hands each element by value so map moves owned Strings down the chain, while iter borrows and leaves the source usable.
Code
fn main() {
let names = vec![String::from("deploy"), String::from("lint"), String::from("test")];
// into_iter hands each element by value: adapters move owned Strings through
let upper: Vec<String> = names
.into_iter()
.map(|name| name.to_uppercase())
.collect();
println!("upper: {upper:?}");
// names was consumed by into_iter; this would not compile:
// println!("{names:?}");
let borrowed = vec!["deploy", "lint", "test"];
// iter yields references instead, so the source stays usable
let lengths: Vec<usize> = borrowed.iter().map(|name| name.len()).collect();
println!("lengths: {lengths:?}");
println!("borrowed still there: {borrowed:?}");
// chain both styles: move one vec's elements, borrow another's
let tags = vec![String::from("eu"), String::from("prod")];
let mixed: Vec<String> = tags
.into_iter()
.chain(borrowed.iter().map(|s| s.to_string()))
.collect();
println!("mixed: {mixed:?}");
}What this snippet actually does — Into Iter Moves Elements Through Adapters
Into Iter Moves Elements Through Adapters reduces to the function main.
Watch out for
- Installation never enters the story: the runtime already has these APIs.
Putting it to use
The entry-point signature is fn main()
The file’s steps show up in the output as upper:, lengths:, borrowed still there:.
Core lines
let lengths: Vec<usize> = borrowed.iter().map(|name| name.len()).collect();
.chain(borrowed.iter().map(|s| s.to_string()))
.collect();
.map(|name| name.to_uppercase())
.collect();
Interactive Tools for This Topic
FAQ
- What does Into Iter Moves Elements Through Adapters print when run?
- Running the file directly is enough — expect labeled output lines such as `upper:`, `lengths:`, `borrowed still there:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.