Concept Flow - Vector creation
Start
Declare Vector
Add elements
Use Vector
End
This flow shows how a vector is created, elements are added, and then the vector is used.
fn main() {
let mut v = Vec::new();
v.push(10);
v.push(20);
println!("{:?}", v);
}| Step | Action | Vector Content | Output |
|---|---|---|---|
| 1 | Declare mutable empty vector v | [] | |
| 2 | Push 10 into v | [10] | |
| 3 | Push 20 into v | [10, 20] | |
| 4 | Print vector v | [10, 20] | [10, 20] |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| v | empty vector [] | [10] | [10, 20] | [10, 20] |
Vector creation in Rust:
- Use let mut v = Vec::new() to create a mutable empty vector.
- Add elements with v.push(value).
- Print vector with println!("{:?}", v).
- Vector must be mutable to add elements.
- Elements are stored in order.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