Rust:Rust Vectors (Vec<T>): Dynamic Heap Arrays and Slices
Rust•Vectors

Rust Vectors (Vec<T>): Dynamic Heap Arrays and Slices

Vec<T> is a growable heap-allocated array providing contiguous memory layout and safe bounds checking.

Syntax

let mut v = vec![1, 2, 3]; v.push(4); let first = v.get(0);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
vec!MacroCreates a new Vector initialized with elements.
get(index)MethodSafely returns Option<&T> with bounds checking.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Rust locally:

fn main() {
    // 1. Initializing vector with vec! macro
    let mut scores = vec![85, 90, 78];

    scores.push(95);
    scores.push(99);

    println!("Vector Length:   {}", scores.len());
    println!("Vector Capacity: {}", scores.capacity());

    // Safe bounds-checked access with .get()
    match scores.get(0) {
        Some(first) => println!("First Score:     {}", first),
        None => println!("Empty vector!"),
    }

    // Sum using iter()
    let sum: i32 = scores.iter().sum();
    println!("Total Sum:       {}", sum);
}
Expected Output:
Vector Length:   5
Vector Capacity: 6
First Score:     85
Total Sum:       447

How It Works: Step-by-Step

  • Lines 3-6: Creates vector and pushes elements dynamically.
  • Lines 12-15: .get(0) returns Option<&i32> for panic-free bounds checking.
  • Line 18: .iter().sum() calculates total sum.

Key Concepts

  • Indexing with v[i] panics on out-of-bounds indices; v.get(i) returns None safely.
  • Vectors manage heap memory automatically via RAII drop.

Common Mistake: Mutating a vector while holding a reference to one of its elements

Rust borrow checker forbids push() while holding &v[0] because reallocation invalidates references.

❌ Incorrect
let first = &scores[0];
scores.push(100); // Compile Error: cannot borrow as mutable because also borrowed as immutable
✅ Correct
// Drop or finish using first before calling scores.push()

Related Rust Tutorials & Compiler

Run and test Rust on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Rust Online Compiler