Iter Versus Into Iter Ownership
Pick iter for shared borrows, iter_mut for in-place edits, and into_iter to consume the collection — each form decides what survives the loop.
Code
#[derive(Debug)]
struct Server {
host: String,
}
fn main() {
let servers = vec![
Server { host: "a.internal".into() },
Server { host: "b.internal".into() },
];
// iter():不可变借用,元素是 &Server,循环后集合仍然可用
let hosts: Vec<&str> = servers.iter().map(|s| s.host.as_str()).collect();
println!("hosts: {hosts:?}");
println!("servers still owned: {}", servers.len());
// iter_mut():可变借用,就地修改,不转移所有权
let mut loads = vec![30u32, 80, 55];
for load in loads.iter_mut() {
*load = load.saturating_sub(10);
}
println!("loads after rebalance: {loads:?}");
// into_iter():消耗集合,元素被移动出去,原变量不再可用
let moved: Vec<String> = servers.into_iter().map(|s| s.host).collect();
println!("moved hosts: {moved:?}");
// 取消注释无法编译:servers 已被消耗
// println!("{servers:?}");
}How it works
Iter Versus Into Iter Ownership comes down to the function main.
Repetition is confined to for load in loads.iter_mut() — the rest of the file is straight-line.
Applying it
The demo output is labeled (hosts:, servers still owned:, loads after rebalance:), so every printed line maps back to its originating operation.
Statements that matter
let hosts: Vec<&str> = servers.iter().map(|s| s.host.as_str()).collect();
let moved: Vec<String> = servers.into_iter().map(|s| s.host).collect();
Interactive Tools for This Topic
FAQ
- What does Iter Versus Into Iter Ownership print when run?
- Run it as a complete program — the output lines carry labels such as `hosts:`, `servers still owned:`, `loads after rebalance:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.