Home
Rust
Array of Vecs Example
Updated Mar 22, 2023
Dot Net Perls
Array, vecs. Suppose we want to store a vector in each element of an array. We must first initialize this array, which can be confusing in Rust.
vec
When initializing arrays, each initial element must be a constant. In Rust we can use a const empty array to satisfy this condition.
Example code. In this example program, we create an array of 10 vectors. Each vector is separate, and represents a separate region of memory.
Start To initialize the array, we use a constant empty vector. This is like a placeholder for each array element.
Here We iterate over the array elements and for each vector, we push 3 integers.
iter
Result In the final for-loop, we see the array has 10 elements and each element is a vector with 3 integers in it.
for
fn main() { // Specify an empty vector as a constant. const EMPTY: Vec<i32> = vec![]; // Initialize the array. let mut array = [EMPTY; 10]; // Loop over the array vectors and push 3 numbers to each one. for array in array.iter_mut() { array.push(1); array.push(2); array.push(3); } // Print the vector data in the array. for array in array.iter() { println!("{:?}", array); } }
[1, 2, 3] [1, 2, 3] [1, 2, 3] [1, 2, 3] [1, 2, 3] [1, 2, 3] [1, 2, 3] [1, 2, 3] [1, 2, 3] [1, 2, 3]
A summary. To create an array of vectors, we must initialize with a constant empty array. This allows the array creation expression to compile correctly.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 22, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen