HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to RustVariablesData TypesOperatorsStringsVectors (Vec)Conditions (if / match)Loops (for / while)FunctionsOwnership & Borrowing
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Vector & HashMap
🔁 Condition & Loop
🧩 Function
🔑 Ownership & Borrowing
Rust›Vectors (Vec)

Vectors (Vec)

Flexible lists: push, len, index, iter().sum() and printing with {:?}.

Simple enough for a 5-year-old to understand

Create and append to a Vec

Example code
1
fn main() {
2
let mut v = vec![1, 2];
mut — mutable Vec.
Datamut — mutable Vec.
3
v.push(3);
Add to the end.
CodeAdd to the end.
4
println!("{:?}", v);
[1, 2, 3] (with {:?})
Output / Input[1, 2, 3] (with {:?})
5
}
DataCodeOutput / Input
💡 Hint: Vec needs to be mut for push. Use {:?} instead of {} to print a Vec.

About this topic

Vec is Rust's growable array and the most commonly used collection. It stores elements contiguously in memory, manages its own size, and frees its memory when it goes out of scope. It corresponds to C++'s vector type.

The safety guarantee Rust adds is bounds checking. If you go out of bounds with index access, the program STOPS with a clean message; unlike in C, it does not read neighboring memory. If you don't want it to stop, the get method reports the presence of a value at the type level.

When working with Vec, the borrowing rule applies: you cannot add elements to the collection while holding a reference to an element. This is because Vec reallocates memory as it grows, making old references invalid. In C++, this is a runtime error; in Rust, the code fails to compile.

What you will learn

  • Creating a Vec and adding elements
  • The difference between indexing and get
  • Why mutating while iterating fails to compile
  • Iterator methods
  • The relationship between ownership and iteration

When to use?

Use Vec when the number of elements is not known upfront, and it is the default collection of choice in Rust.

If you know how many elements there will be, reserving space upfront with with_capacity eliminates reallocations during growth.

If you frequently add and remove elements, Vec is inefficient because subsequent elements have to be shifted.

Common mistakes

Wrong

fn main() {
    let numbers = vec![1, 2, 3];
    numbers.push(4);
    println!("{:?}", numbers);
}

Since the variable is not defined as mut, methods that modify it cannot be called; the compiler gives a "cannot borrow numbers as mutable" error and suggests adding mut. In Rust, mutation privileges must be explicitly declared.

Correct

fn main() {
    let mut numbers = vec![1, 2, 3];
    numbers.push(4);
    println!("{:?}", numbers);
}

Wrong

fn main() {
    let numbers = vec![1, 2, 3];
    println!("{}", numbers[10]);
}

Since the index is out of bounds, the program STOPS: "index out of bounds: the len is 3 but the index is 10". Unlike in C, it doesn't read garbage data, it terminates with a clean message. If you don't want it to stop, the get method indicates at the type level that the value might not exist.

Correct

fn main() {
    let numbers = vec![1, 2, 3];
    match numbers.get(10) {
        Some(value) => println!("{}", value),
        None => println!("This index does not exist"),
    }
}

Wrong

fn main() {
    let mut numbers = vec![1, 2, 3];
    let first = &numbers[0];
    numbers.push(4);
    println!("{}", first);
}

You cannot add to the collection while holding a reference to an element; the compiler gives a "cannot borrow numbers as mutable because it is also borrowed as immutable" error. The real reason: Vec relocates memory as it grows, leaving the old reference dangling. C++ compiles this and crashes at runtime.

Correct

fn main() {
    let mut numbers = vec![1, 2, 3];
    let first = numbers[0];
    numbers.push(4);
    println!("{}", first);
}

Frequently asked questions

Which one should I use, indexing or get?

If you are sure the index is valid, square brackets are shorter. If the index comes from user input or calculation, use get: it indicates at the type level that the value might not be there, and the program won't stop.

Why can't I use the Vec after iterating over it?

Iterating directly transfers ownership, so the Vec gets consumed. If you start the iteration by providing a reference, ownership is retained and you can continue using it afterwards. Writing & in a range-based loop achieves this.

Can I delete elements while iterating?

Directly no, the compiler prevents it. Rust's way is the retain method: you provide a condition, and elements that don't meet the condition are deleted in a single pass. This is both safe and more efficient than a manually written loop.

Summary

Vec is a growable array and manages its own memory.

mut is required to modify it; otherwise, a compilation error occurs.

An out-of-bounds index stops the program; get reports the absence of a value.

You cannot add elements while holding a reference to an element — the compiler prevents dangling references.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code