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.
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
-loop. These are accessed with the first number of in brackets.for
-loops that add nested vectors at the keys 0 and 4.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
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.
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.