In Place Refresh With Vec::clone_from

Refresh a Vec in place with clone_from so an existing buffer can absorb new contents without reallocating a fresh clone.

RustData Integrity

Code

rustsnippet
20 lines
fn main() {
    let snapshot = vec![1u8, 2, 3, 4];

    // 复用缓冲区:先持有一块旧内存
    let mut buffer: Vec<u8> = vec![9, 9, 9];
    buffer.clone_from(&snapshot);
    assert_eq!(buffer, snapshot);
    println!("buffer refreshed: {buffer:?}");

    // 对照:clone 会产生全新分配
    let fresh = snapshot.clone();
    assert_eq!(fresh, snapshot);
    println!("fresh clone: {fresh:?}");

    // 反复更新同一缓冲区时,clone_from 让容量得以保留
    for round in 1..=2 {
        buffer.clone_from(&vec![round; 4]);
        println!("round {round} buffer: {buffer:?}");
    }
}

What the code does

In Place Refresh With Vec::clone_from keeps everything in the function main.

Iteration happens inside for round in 1..=2 — everything outside it runs once.

Applying it

Output lines are prefixed (buffer refreshed:, fresh clone:, round), making each step’s effect easy to spot.

Statements that matter

let mut buffer: Vec<u8> = vec![9, 9, 9];
buffer.clone_from(&vec![round; 4]);
let snapshot = vec![1u8, 2, 3, 4];

Interactive Tools for This Topic

FAQ

What does In Place Refresh With Vec::clone_from print when run?
Running the file directly is enough — expect labeled output lines such as `buffer refreshed:`, `fresh clone:`, `round`.