Creating two dimensional arrays in Rust Creating two dimensional arrays in Rust arrays arrays

Creating two dimensional arrays in Rust


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;


Editor's note: This answer predates Rust 1.0 and some of the concepts and syntax have changed. Other answers apply to Rust 1.0.

Do you want the contents of the array to be mutable or the variable that holds it? If you want mutable contents, does this work for you?

let mut state = [[0u8; 4]; 4];

If you want the variable to be mutable but not the contents, try this:

let mut state = [[0u8; 4]; 4];

Does this help? I didn't actually compile this, so the syntax might be slightly off.


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;}