Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Rust Dictionary

  1. Home
  2. Rust Dictionary
  3. Vec::new() / vec![]

Vec::new() / vec![]

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

// Creates an empty Vec.
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!["apple", "banana", "cherry"];

// Pre-allocates capacity for performance optimization.
let mut v: Vec<i32> = Vec::with_capacity(100);

// Creates a Vec filled with the same value.
let v = vec![0; 5];  // [0, 0, 0, 0, 0]

// Creates a Vec from an iterator.
let v: Vec<i32> = (1..=5).collect();  // [1, 2, 3, 4, 5]

Creation Methods

SyntaxDescription
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

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);

    // Creates a Vec with initial values using the vec! macro.
    let v2 = vec![10, 20, 30, 40, 50];
    println!("vec![]: {:?}", v2);

    // Creates a Vec filled with the same value.
    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());

    // Creates a Vec from an iterator.
    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!();
}

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 .