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

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Rust Fundamentals

Lesson 16 of 50 · rust

Collections: Vec

Duration: 14 minutes

Collections: Vec\n\nVec<T> (vector) is a growable array allocated on the heap. It's one of Rust's most-used collections.\n\n## Creating Vectors\n\nrust\nfn main() {\n // Empty vector\n let mut v: Vec<i32> = Vec::new();\n \n // Vec macro with initial values\n let v2 = vec![1, 2, 3];\n \n // Vec with repeated values\n let v3 = vec![5; 3]; // [5, 5, 5]\n}\n\n\n## Adding Elements\n\nrust\nfn main() {\n let mut v = Vec::new();\n v.push(1);\n v.push(2);\n v.push(3);\n println!(\"{:?}\", v); // [1, 2, 3]\n}\n\n\n## Reading Elements\n\nTwo ways to access elements with different behaviors:\n\nrust\nlet v = vec![1, 2, 3];\n\n// Using indexing (panics if out of bounds)\nprintln!(\"Element: {}\", v[0]); // 1\n// println!(\"Element: {}\", v[10]); // panics!\n\n// Using get (returns Option)\nmatch v.get(0) {\n Some(val) => println!(\"Element: {}\", val),\n None => println!(\"No element at index\"),\n}\n\n\n## Iterating Vectors\n\nrust\nlet v = vec![1, 2, 3];\n\n// Immutable iteration\nfor item in &v {\n println!(\"Item: {}\", item);\n}\n\n// Mutable iteration\nlet mut v = vec![1, 2, 3];\nfor item in &mut v {\n *item += 1; // Dereference to modify\n}\n\n// Consume vector\nlet v = vec![1, 2, 3];\nfor item in v {\n println!(\"Item: {}\", item); // v is consumed\n}\n// println!(\"{:?}\", v); // ERROR: v is moved\n\n\n## Useful Methods\n\nrust\nlet mut v = vec![1, 2, 3];\n\nprintln!(\"Length: {}\", v.len()); // 3\nprintln!(\"Capacity: {}\", v.capacity()); // At least 3\nprintln!(\"Is empty: {}\", v.is_empty()); // false\n\nlet last = v.pop(); // Some(3), v is now [1, 2]\nv.clear(); // Remove all elements\n\n\n## Working with Generic Vectors\n\nrust\nstruct User {\n name: String,\n age: u32,\n}\n\nfn main() {\n let mut users: Vec<User> = Vec::new();\n \n users.push(User {\n name: String::from(\"Alice\"),\n age: 30,\n });\n \n for user in &users {\n println!(\"{}: {}\", user.name, user.age);\n }\n}\n\n\n## Practical Example\n\nrust\nfn sum_vector(v: &Vec<i32>) -> i32 {\n let mut sum = 0;\n for &num in v {\n sum += num;\n }\n sum\n}\n\nfn double_all(v: &mut Vec<i32>) {\n for item in v {\n *item *= 2;\n }\n}\n\nfn main() {\n let mut numbers = vec![1, 2, 3, 4, 5];\n println!(\"Sum: {}\", sum_vector(&numbers)); // 15\n double_all(&mut numbers);\n println!(\"Doubled: {:?}\", numbers); // [2, 4, 6, 8, 10]\n}\n\n\n## Memory Efficiency\n\nVectors allocate in chunks (capacity > length):\n\n```rust\nlet mut v: Vec = Vec::new();\nprintln!("Capacity: {}", v.capacity()); // 0\n\nv.push(1);

println!("Capacity after push: {}", v.capacity()); // Usually 1\n\nfor i in 2..=10 {\n v.push(i);\n}\nprintln!("Final capacity: {}", v.capacity()); // Likely 16\n\n\nUse `reserve()` if you know approximate size:\n\nrust\nlet mut v = Vec::new();\nv.reserve(1000); // Allocate for 1000 elements\n```

Previous: Pattern MatchingNext: Collections: HashMap