Vec Iteration Patterns

Pick between iter, into_iter, and iter_mut deliberately — each gives a different element type and consumes the vector differently.

RustData Integrity

Code

rustsnippet
18 lines
fn main() {
    let mut scores = vec![10, 20, 30];

    // iter:&i32 只读借用,Vec 完好
    let total: i32 = scores.iter().sum();
    println!("total: {}", total);

    // iter_mut:&mut i32 就地修改
    for s in scores.iter_mut() {
        *s += 1;
    }
    println!("after bump: {:?}", scores);

    // into_iter:消耗 Vec,元素按值交付
    let doubled: Vec<i32> = scores.into_iter().map(|s| s * 2).collect();
    println!("doubled: {:?}", doubled);
    // println!("{:?}", scores); // 已被消耗:编译错误
}

How the snippet works

Vec Iteration Patterns is built around the function main.

for s in scores.iter_mut() is the loop that carries the per-item work.

Using it

The demo output is labeled (total:, after bump:, doubled:), so every printed line maps back to its originating operation.

Key statements

let doubled: Vec<i32> = scores.into_iter().map(|s| s * 2).collect();
let total: i32 = scores.iter().sum();

Interactive Tools for This Topic

FAQ

What does Vec Iteration Patterns print when run?
Invoke the file as-is — the `total:`, `after bump:`, `doubled:` prefixes identify which step printed each line.