Creating two dimensional arrays in Rust
You can create a dynamically-sized 2D vector like this:
fn example(width: usize, height: usize) {
// Base 1d array
let mut grid_raw = vec![0; width * height];
// Vector of 'width' elements slices
let mut grid_base: Vec<_> = grid_raw.as_mut_slice().chunks_mut(width).collect();
// Final 2d array `&mut [&mut [_]]`
let grid = grid_base.as_mut_slice();
// Accessing data
grid[0][0] = 4;
}
In Rust 1.0, the following works:
let mut state = [[0u8; 4]; 6];
state[0][1] = 42;
Note that the length of the interior segment is an integral part of the type. For example, you can reference (and pass) state
as follows:
let a: &[[u8; 4]] = &state;
but not without specifying the fixed length of the sub-array. If you need variable length sub-arrays you may need to do something like this:
let x: [Box<[u8]>; 3] = [
Box::new([1, 2, 3]),
Box::new([4]),
Box::new([5, 6])
];
let y: &[Box<[u8]>] = &x;