Split Off Partitions A Vec At Index

Vec::split_off keeps the first part in place and hands back everything from an index, giving in-place partitioning for batch loops with no extra copy.

RustData Integrity

Code

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

    // split_off(2):前半段留在原 Vec,[30, 40, 50] 作为新 Vec 返回
    let tail = scores.split_off(2);
    println!("head: {scores:?}");
    println!("tail: {tail:?}");

    // at == len 合法:切出空尾
    let empty = scores.split_off(scores.len());
    println!("tail empty: {empty:?}");

    // at > len 会 panic(合法区间是 0 <= at <= len)
    // scores.split_off(99);

    // 分批处理:反复从尾部切走固定大小的批次
    let mut jobs: Vec<u32> = (1..=7).collect();
    while !jobs.is_empty() {
        let cut = jobs.len().min(3);
        let batch = jobs.split_off(jobs.len() - cut);
        println!("batch: {batch:?}");
    }
}

What this snippet does

Split Off Partitions A Vec At Index comes down to the function main.

A single loop drives the file — while !jobs.is_empty().

Watch out for

  • Purely standard-library — copy it in and it runs.

Applying it

The signature to read first: fn main()

Output lines are prefixed (head:, tail:, tail empty:), so the outcome of each step is easy to trace.

Statements that matter

let mut jobs: Vec<u32> = (1..=7).collect();

Interactive Tools for This Topic

FAQ

What does Split Off Partitions A Vec At Index print when run?
Run it as a complete program — the output lines carry labels such as `head:`, `tail:`, `tail empty:`.