IntoIterator & Owned vs Borrowed
IntoIterator converts into iterator. Three modes: iter() shared borrow, iter_mut() mutable borrow, into_iter() owned consume.
Busca en todas las páginas de la documentación
IntoIterator converts into iterator. Three modes: iter() shared borrow, iter_mut() mutable borrow, into_iter() owned consume.
fn main() {
let v = vec![1, 2, 3];
for x in &v { print!("{x} "); }
for x in v.into_iter() { print!("{x} "); }
}When to reach for this: Choosing whether for moves, borrows, or mutates elements.
fn total_borrowed(v: &Vec<i32>) -> i32 {
v.iter().sum()
}
fn total_owned(v: Vec<i32>) -> i32 {
v.into_iter().sum()
}
fn main() {
let data = vec![1, 2, 3];
println!("{} {}", total_borrowed(&data), data.len());
println!("{}", total_owned(data));
}What this demonstrates:
iter keeps data usable after suminto_iter consumes datafor x in collection calls into_iter on collection. &collection uses IntoIterator for &Vec yielding &T.
Arrays [T; N] implement IntoIterator copying elements if Copy.
for x in &vec.&mut T.impl IntoIterator or generic I: IntoIterator.
| Alternative | Use When | Don't Use When |
|---|---|---|
| Index loop | Need index + neighbors | Idiomatic for each |
drain | Remove subset | Full consume |
as_slice iteration | Explicit slice | iter() same |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 19 jul 2026