Array IntoIterator Owns By Value

Since Rust 2021, for loops consume arrays by value through IntoIterator; contrast iter() borrows with owned iteration and moves.

RustData Integrity

Code

rustsnippet
23 lines
fn main() {
    let arr: [String; 3] = [String::from("alpha"), String::from("beta"), String::from("gamma")];

    // arrays implement IntoIterator by value since Rust 2021
    // 先借用迭代:.iter() 产出 &String,arr 仍可用
    let refs: Vec<&String> = arr.iter().collect();
    println!("refs: {refs:?}");
    let joined = arr.join("-");
    println!("joined: {joined}");

    // for 直接按值(owns)消费元素:String 不是 Copy,数组随之被真正 move
    let upper: Vec<String> = {
        let mut out = Vec::new();
        for n in arr {
            out.push(n.to_uppercase());
        }
        out
    };
    println!("upper: {upper:?}");

    // arr 已被 move:此后再用它编译报错(String 非 Copy,按值消费即转移所有权)
    // println!("{}", arr[0]);
}

Inside the snippet

Array IntoIterator Owns By Value is built around the function main.

Iteration happens inside for n in arr — everything outside it runs once.

Putting it to use

Running the file prints labeled results such as refs:, joined:, upper: — each operation’s effect is visible in the output.

Core lines

let refs: Vec<&String> = arr.iter().collect();

Interactive Tools for This Topic

FAQ

What does Array IntoIterator Owns By Value print when run?
Run it as a complete program — the output lines carry labels such as `refs:`, `joined:`, `upper:`.