Introduction
A vector is a list that can grow or shrink. You use it to store many values in order.
A vector is a list that can grow or shrink. You use it to store many values in order.
let v: Vec<T> = Vec::new(); // or with values let v = vec![value1, value2, value3];
Vec::new() creates an empty vector.
vec![...] creates a vector with initial values.
let numbers: Vec<i32> = Vec::new();let fruits = vec!["apple", "banana", "cherry"];
let mut scores = Vec::new(); scores.push(10); scores.push(20);
This program creates a vector with two colors, adds one more, and prints all colors.
fn main() {
let mut colors = vec!["red", "green"];
colors.push("blue");
for color in &colors {
println!("{}", color);
}
}Vectors grow automatically when you add items with push.
You need mut to change (add/remove) items in a vector.
Use &vector to borrow the vector for reading without changing it.
Vectors store multiple values in order and can change size.
Create vectors empty with Vec::new() or with values using vec![...].
Use push to add items and loops to read them.
Vec::new() with the type specified if needed.Vec::new() with type i32, which is correct. let v = vec!(); uses vec!() which is invalid syntax. let v = Vector::new(); uses Vector::new() which is not a Rust type. let v = vec![0]; creates a vector with one element 0, not empty.vec![...] with square brackets and exclamation mark to create vectors with initial values.vec![1, 2, 3]. let v = Vec[1, 2, 3]; uses square brackets without exclamation mark, invalid. let v = vec(1, 2, 3); uses parentheses, invalid. let v = vec{1, 2, 3}; uses curly braces, invalid.let mut v = Vec::new();
v.push(10);
v.push(20);
println!("{:?}", v);push(10) adds 10 at the end, then push(20) adds 20 after 10.println!("{:?}", v) prints the vector in debug format showing all elements in order: [10, 20].let v = Vec::new(); v.push(5);
v is declared without mut, so it is immutable by default.push method requires the vector to be mutable to add elements. Trying to push to an immutable vector causes a compile error.String using iter(), map() with to_string(), then collect().push with "d".to_string() to add a new string.Pass the test and this pattern moves unknown