Vec::new() / vec![]
| Since: | Rust 1.0(2015) |
|---|
A Vec (vector) in Rust is a dynamically sized array. Use Vec::new() to create an empty Vec, or the vec![] macro to create one with initial values. Use a Vec when you need to manage a collection of elements of the same type that can grow or shrink at runtime.
Syntax
let v: Vec<i32> = Vec::new(); // Creates a Vec with initial values using the vec! macro (type inference applies). let v = vec![1, 2, 3, 4, 5]; let v = vec!["user_a", "user_c", "user_d"]; // Pre-allocates capacity for performance optimization. let mut v: Vec<i32> = Vec::with_capacity(100); let v = vec![0; 5]; // [0, 0, 0, 0, 0] let v: Vec<i32> = (1..=5).collect(); // [1, 2, 3, 4, 5]
Creation Methods
| Syntax | Description |
|---|---|
| Vec::new() | Creates an empty Vec (element type is specified with a type annotation). |
| vec![val1, val2, ...] | Creates a Vec with initial values (type inference applies). |
| vec![val; n] | Creates a Vec containing n copies of the given value. |
| Vec::with_capacity(n) | Creates a Vec with memory pre-allocated for n elements. |
| iterator.collect::<Vec<_>>() | Collects iterator elements into a Vec. |
| v.capacity() | Returns the number of elements the Vec can hold without reallocating. |
| v.len() | Returns the current number of elements. |
| v.is_empty() | Returns whether the Vec is empty. |
| v[i] | Accesses the element at index i (panics if out of bounds). |
| v.get(i) | Returns the element at index i as Option<&T> (returns None if out of bounds). |
Sample Code
sample_vec_new.rs
fn main() {
// Creates an empty Vec using Vec::new().
let mut v1: Vec<i32> = Vec::new();
v1.push(1);
v1.push(2);
v1.push(3);
println!("Vec::new() + push: {:?}", v1);
let v2 = vec![10, 20, 30, 40, 50];
println!("vec![]: {:?}", v2);
let zeros = vec![0; 5];
println!("vec![0; 5]: {:?}", zeros);
// Pre-allocates memory using Vec::with_capacity.
let mut v3: Vec<i32> = Vec::with_capacity(10);
println!("\nAfter pre-allocation: len={}, capacity={}", v3.len(), v3.capacity());
for i in 0..5 {
v3.push(i);
}
println!("After adding 5 elements: len={}, capacity={}", v3.len(), v3.capacity());
let v4: Vec<i32> = (1..=5).collect();
println!("\n(1..=5).collect(): {:?}", v4);
let v5: Vec<i32> = (0..10).filter(|x| x % 2 == 0).collect();
println!("Even numbers only: {:?}", v5);
// Accessing elements.
println!("\n--- Element Access ---");
let v = vec![10, 20, 30, 40, 50];
println!("v[2] = {}", v[2]); // Index access
// Safe access with get() returns an Option type.
match v.get(2) {
Some(x) => println!("v.get(2) = {}", x),
None => println!("Index out of bounds"),
}
println!("v.get(10) = {:?}", v.get(10)); // None
// Vec metadata.
println!("\n--- Metadata ---");
println!("len: {}", v.len());
println!("is_empty: {}", v.is_empty());
println!("capacity: {}", v.capacity());
// Iterating with a for loop.
print!("\nfor loop: ");
for x in &v {
print!("{} ", x);
}
println!();
}
Compile with the following command:
rustc vec_new.rs ./vec_new Vec::new() + push: [1, 2, 3] vec![]: [10, 20, 30, 40, 50] vec![0; 5]: [0, 0, 0, 0, 0] After pre-allocation: len=0, capacity=10 After adding 5 elements: len=5, capacity=10 (1..=5).collect(): [1, 2, 3, 4, 5] Even numbers only: [0, 2, 4, 6, 8] --- Element Access --- v[2] = 30 v.get(2) = 30 v.get(10) = None --- Metadata --- len: 5 is_empty: false capacity: 5 for loop: 10 20 30 40 50
Common Mistakes
Mistake 1: Forgetting the type annotation with Vec::new(), causing a compile error
When using Vec::new() without specifying the element type via a type annotation, the compiler cannot infer the type and will produce an error. This is especially important when push() is called later.
vec_new_mistake1.rs
fn main() {
// Without a type annotation, the type cannot be inferred when pushing later.
let v = Vec::new();
// v.push(1); // Adding this line would allow inference, but...
// Passing an empty Vec to a for loop causes an error.
for x in &v {
println!("{}", x); // error: type annotations needed
}
}
Compile with the following command:
rustc vec_new_mistake1.rs error[E0282]: type annotations needed
Provide an explicit type annotation or supply initial values with the vec! macro.
vec_new_fix1.rs
fn main() {
// Add a type annotation.
let mut v1: Vec<i32> = Vec::new();
v1.push(1);
v1.push(2);
println!("{:?}", v1);
// Type inference works with the vec! macro.
let v2 = vec![1, 2, 3];
println!("{:?}", v2);
// Specify the type when using collect.
let v3: Vec<i32> = (1..=5).collect();
println!("{:?}", v3);
}
Compile with the following command:
rustc vec_new_fix1.rs ./vec_new_fix1 [1, 2] [1, 2, 3] [1, 2, 3, 4, 5]
Mistake 2: Ownership of the Vec moves into the for loop with for x in v, making it unavailable afterward
Writing for x in v moves ownership of v into the loop. Attempting to use v after the loop results in a compile error.
vec_new_mistake2.rs
fn main() {
let v = vec![1, 2, 3, 4, 5];
for x in v { // Ownership of v moves into the loop.
println!("{}", x);
}
// v is no longer available.
// println!("{:?}", v); // Compile error
}
Compile with the following command:
rustc vec_new_mistake2.rs ./vec_new_mistake2 1 2 3 4 5
To use v after the loop, pass a reference with &v.
vec_new_fix2.rs
fn main() {
let v = vec![1, 2, 3, 4, 5];
for x in &v { // &v passes a reference (ownership does not move).
println!("{}", x);
}
// v is still available after the loop.
println!("Sum: {}", v.iter().sum::<i32>());
}
Compile with the following command:
rustc vec_new_fix2.rs ./vec_new_fix2 1 2 3 4 5 Sum: 15
Notes
Pre-allocating memory with Vec::with_capacity() prevents repeated memory reallocations as elements are added. If you know the approximate number of elements in advance, using this method can improve performance.
There are two ways to access elements: by index (v[i]) and with get(). Index access panics if the index is out of bounds, whereas get() returns an Option type for safe access. Use get() when working with user input or external data.
When iterating over a Vec with a for loop, use &v (a reference) to avoid moving ownership. Writing for x in v without the & transfers ownership of v, making it unavailable afterward.
For adding and removing elements, see Vec::push() / pop() / insert() / remove().
If you find any errors or copyright issues, please contact us.