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.
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.
Vec<T> š”To create a new Vec<T>, you can use the vec! macro. Here's an example of creating a Vec<i32>:
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.
Vec<T> šTo access elements in a Vec<T>, you can use indexing just like in arrays. Here's an example:
let numbers: Vec<i32> = vec![1, 2, 3, 4, 5];
let third_number = numbers[2]; // third_number will have the value 3Vec<T> š”To change an element in a Vec<T>, you can assign a new value to the corresponding index. Here's an example:
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.
Vec<T> šTo add an element to a Vec<T>, you can use the push() method. Here's an example:
let mut numbers: Vec<i32> = vec![1, 2, 3, 4, 5];
numbers.push(6); // Now numbers will be [1, 2, 3, 4, 5, 6]Vec<T> š”To remove an element from a Vec<T>, you can use the pop() method. Here's an example:
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]Vec<T> šTo iterate over a Vec<T>, you can use the iter() method. Here's an example:
let numbers: Vec<i32> = vec![1, 2, 3, 4, 5];
for number in numbers.iter() {
println!("{}", number);
}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:
let numbers: Vec<i32> = vec![1, 2, 3, 4, 5];
let slice: &[i32] = &numbers[1..3]; // slice will be [2, 3]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! š