Vec Operations Ownership Rules

Show which Vec operations move versus borrow — push, drain, split_off, iter_mut — so half-moved collections fail at compile time, not in review.

RustData Integrity

Code

rustsnippet
29 lines
#[derive(Debug)]
struct Task {
    name: String,
    done: bool,
}

fn main() {
    let mut tasks = vec![
        Task { name: "pack".into(), done: false },
        Task { name: "ship".into(), done: false },
        Task { name: "bill".into(), done: true },
    ];

    // 可变借用:iter_mut 就地修改,不转移所有权
    for task in tasks.iter_mut() {
        if task.name == "pack" {
            task.done = true;
        }
    }

    // drain 按谓词拆分:done 的移出,其余留在原 Vec
    tasks.retain(|t| !t.done);
    println!("open tasks: {:?}", tasks);

    // split_off 把尾部所有权整体转移给新 Vec
    let mut queue = vec![1, 2, 3, 4, 5];
    let tail = queue.split_off(3);
    println!("head {:?} tail {:?}", queue, tail);
}

How the snippet works

Vec Operations Ownership Rules comes down to the function main.

Repetition is confined to for task in tasks.iter_mut() — the rest of the file is straight-line.

Applying it

Running the file prints labeled results such as open tasks:, head — each operation’s effect is visible in the output.

Statements that matter

let mut queue = vec![1, 2, 3, 4, 5];
let tail = queue.split_off(3);
tasks.retain(|t| !t.done);

Interactive Tools for This Topic

FAQ

What does Vec Operations Ownership Rules print when run?
Execute the whole file; each printed line is prefixed with a label like `open tasks:`, `head`.