Home
Rust
Vec Nested Example
Updated Feb 22, 2023
Dot Net Perls
Nested vec. Consider data that should be addressed by 2 integer keys—for example, an X and Y position. Nested vectors can store this data in Rust efficiently.
In Rust, we can use an empty vector to create the first containing vector. Then we add inner vectors to represent the second dimensions. We can access the elements directly.
vec
Vec Equals
An example. To begin, we create a mutable local variable called "data" and specify it as a nested vector type. The element type is a 32-bit signed integer (i32).
Start We create the initial vectors in a for-loop. These are accessed with the first number of in brackets.
for
Next We can push to the first level of vectors we just added. We have 2 for-loops that add nested vectors at the keys 0 and 4.
Result We print the vectors. We can also assign and test elements of the nested vectors.
fn main() { // Create a vector of vectors. let mut data: Vec<Vec<i32>> = vec![]; // Add initial vectors. for _ in 0..8 { data.push(vec![]); } // Add nested vectors. let key = 0; for i in 5..10 { data[key].push(i); } // Add another nested vector. let key = 4; for i in 0..5 { data[key].push(i); } println!("{:?}", data); // Change an element. data[0][0] = 999; println!("{:?}", data); // Test an element. if data[4][1] == 1 { println!("OK"); } }
[[5, 6, 7, 8, 9], [], [], [], [0, 1, 2, 3, 4], [], [], []] [[999, 6, 7, 8, 9], [], [], [], [0, 1, 2, 3, 4], [], [], []] OK
Some comments. Nested vectors are a powerful and useful approach to storing data in "buckets" as a program runs. This can reduce the need for collections and speed up programs.
A summary. With Rust, some types are inferred by the compiler—this simplifies syntax and makes programs easier to read. With nested vectors, this feature helps program clarity.
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 Feb 22, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen