Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Collections: Vec | Rust Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. Rust Fundamentals

Lesson 16 of 50

·rust

Collections: Vec

14 minutes

Course progress32%

Collections: Vec

Vec<T> (vector) is a growable array allocated on the heap. It's one of Rust's most-used collections.

Creating Vectors

fn main() {
    // Empty vector
    let mut v: Vec<i32> = ::();
    
    
      = [, , ];
    
    
      = [; ];  
}
Vec
new
// Vec macro with initial values
let
v2
vec!
1
2
3
// Vec with repeated values
let
v3
vec!
5
3
// [5, 5, 5]

Adding Elements

fn main() {
    let mut v = Vec::new();
    v.push(1);
    v.push(2);
    v.push(3);
    println!(\"{:?}\", v);  // [1, 2, 3]
}

Reading Elements

Two ways to access elements with different behaviors:

let v = vec![1, 2, 3];

// Using indexing (panics if out of bounds)
println!(\"Element: {}\", v[0]);  // 1
// println!(\"Element: {}\", v[10]);  // panics!

// Using get (returns Option)
match v.get(0) {
    Some(val) => println!(\"Element: {}\", val),
    None => println!(\"No element at index\"),
}

Iterating Vectors

let v = vec![1, 2, 3];

// Immutable iteration
for item in &v {
    println!(\"Item: {}\", item);
}

// Mutable iteration
let mut v = vec![1, 2, 3];
for item in &mut v {
    *item += 1;  // Dereference to modify
}

// Consume vector
let v = vec![1, 2, 3];
for item in v {
    println!(\"Item: {}\", item);  // v is consumed
}
// println!(\"{:?}\", v);  // ERROR: v is moved

Useful Methods

let mut v = vec![1, 2, 3];

println!(\"Length: {}\", v.len());       // 3
println!(\"Capacity: {}\", v.capacity()); // At least 3
println!(\"Is empty: {}\", v.is_empty()); // false

let last = v.pop();  // Some(3), v is now [1, 2]
v.clear();           // Remove all elements

Working with Generic Vectors

struct User {
    name: String,
    age: u32,
}

fn main() {
    let mut users: Vec<User> = Vec::new();
    
    users.push(User {
        name: String::from(\"Alice\"),
        age: 30,
    });
    
    for user in &users {
        println!(\"{}: {}\", user.name, user.age);
    }
}

Practical Example

fn sum_vector(v: &Vec<i32>) -> i32 {
    let mut sum = 0;
    for &num in v {
        sum += num;
    }
    sum
}

fn double_all(v: &mut Vec<i32>) {
    for item in v {
        *item *= 2;
    }
}

fn main() {
    let mut numbers = vec![1, 2, 3, 4, 5];
    println!(\"Sum: {}\", sum_vector(&numbers));  // 15
    double_all(&mut numbers);
    println!(\"Doubled: {:?}\", numbers);  // [2, 4, 6, 8, 10]
}

Memory Efficiency

Vectors allocate in chunks (capacity > length):

let mut v: Vec<i32> = Vec::new();
println!(\"Capacity: {}\", v.capacity());  // 0

v.push(1);
println!(\"Capacity after push: {}\", v.capacity());  // Usually 1

for i in 2..=10 {
    v.push(i);
}
println!(\"Final capacity: {}\", v.capacity());  // Likely 16

Use reserve() if you know approximate size:

let mut v = Vec::new();
v.reserve(1000);  // Allocate for 1000 elements
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities
Previous lessonPattern MatchingContinue to lesson 17Collections: HashMapBack to Rust Fundamentals curriculum