std-method

Initialize Vec spare capacity before extending length

Capacity is reserved space, whereas length counts live elements. Write into the spare slots and expose only the initialized prefix by increasing length. This example uses Copy bytes so no owned resources can leak if initialization is interrupted; prefer extend_from_slice for ordinary appending. Expected stdout (not executed): [10, 20, 30] Common mistake: Setting length to capacity even though some slots were never written.

Formal Syntax & Structure

rust syntaxrust
vec.spare_capacity_mut(); unsafe { vec.set_len(new_len) }

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    let mut bytes = Vec::<u8>::with_capacity(4);    bytes.push(10);    let old_len = bytes.len();    let spare = bytes.spare_capacity_mut();    spare[0].write(20);    spare[1].write(30);    // SAFETY: old_len + 2 <= capacity and both added elements were initialized.    // The spare borrow has ended, and all prior elements are still initialized.    unsafe { bytes.set_len(old_len + 2); }    println!("{bytes:?}");}
Rust Reference