Home
Search
Rust Nested vec ExamplePlace a vector in another vector to achieve a nested vec or a two-dimensional vec of integers.
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).
For We create the initial vectors in a for-loop. These are accessed with the first number of in brackets.
for
Nested vectors 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.
Home
© 2007-2022 sam allen.
see site info on the changelog.