Vec<T> (Vector) in Rust: Your Comprehensive Guide šŸŽÆ

beginner
23 min

Vec<T> (Vector) in Rust: Your Comprehensive Guide šŸŽÆ

Welcome to this detailed tutorial on Vec<T> (Vector) in Rust! In this lesson, we'll dive deep into understanding this essential data structure, its usage, and real-world applications. By the end of this tutorial, you'll have a solid foundation to work with Vec<T> in your own projects.

What is Vec<T>? šŸ“

Vec<T> stands for Vector, and it's a dynamic-sized, resizable array in Rust. You can think of it as an array that can change its size at runtime. It's one of the fundamental types in Rust and is used frequently in most projects.

Creating a Vec<T> šŸ’”

To create a new Vec<T>, you can use the vec! macro. Here's an example of creating a Vec<i32>:

rust
let numbers: Vec<i32> = vec![1, 2, 3, 4, 5];

šŸ’” Pro Tip: Replace i32 with any other data type you need, such as String, f64, or even your own custom types.

Accessing Elements in a Vec<T> šŸ“

To access elements in a Vec<T>, you can use indexing just like in arrays. Here's an example:

rust
let numbers: Vec<i32> = vec![1, 2, 3, 4, 5]; let third_number = numbers[2]; // third_number will have the value 3

Changing Elements in a Vec<T> šŸ’”

To change an element in a Vec<T>, you can assign a new value to the corresponding index. Here's an example:

rust
let mut numbers: Vec<i32> = vec![1, 2, 3, 4, 5]; numbers[2] = 10; // Now numbers will be [1, 2, 10, 4, 5]

šŸ’” Pro Tip: To modify a Vec<T>, make sure to use the mut keyword before the Vec declaration.

Adding Elements to a Vec<T> šŸ“

To add an element to a Vec<T>, you can use the push() method. Here's an example:

rust
let mut numbers: Vec<i32> = vec![1, 2, 3, 4, 5]; numbers.push(6); // Now numbers will be [1, 2, 3, 4, 5, 6]

Removing Elements from a Vec<T> šŸ’”

To remove an element from a Vec<T>, you can use the pop() method. Here's an example:

rust
let mut numbers: Vec<i32> = vec![1, 2, 3, 4, 5]; let popped_number = numbers.pop(); // popped_number will have the value Some(5) and numbers will be [1, 2, 3, 4]

Iterating over a Vec<T> šŸ“

To iterate over a Vec<T>, you can use the iter() method. Here's an example:

rust
let numbers: Vec<i32> = vec![1, 2, 3, 4, 5]; for number in numbers.iter() { println!("{}", number); }

Slices and Vec<T> šŸ’”

A slice is a reference to a contiguous portion of a Vec<T>. You can create a slice by referencing a part of a Vec<T>> using square brackets. Here's an example:

rust
let numbers: Vec<i32> = vec![1, 2, 3, 4, 5]; let slice: &[i32] = &numbers[1..3]; // slice will be [2, 3]

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

What is the output of the following code?

Stay tuned for more in-depth lessons on Vec<T> in Rust! We'll cover topics like vector capacity, vector resizing, and advanced techniques to optimize your code. Happy learning! šŸŽ‰