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.
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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 22, 2023 (edit).