Creating two dimensional arrays in Rust

rust 2d array in struct
rust two dimensional vector
rust arrays
rust initialize 2d array
rust vector
rust multidimensional array as argument
rust static array
rust variable length array

How do I create an empty mutable two dimensional array in Rust?

This is what I have tried so far:

let mut state[[u8 * 4] * 4];

This produces the error

error: expected one of `:`, `;`, `=`, or `@`, found `[`
 --> src/main.rs:2:18
  |
2 |     let mut state[[u8 * 4] * 4];
  |                  ^ expected one of `:`, `;`, `=`, or `@` here

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 state = [mut [mut 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.

Create a 2-dimensional array, in Rust, Idiom #26 Create a 2-dimensional array. Declare and initialize a matrix x having m rows and n columns, containing real numbers. Illustration. Rust · Rust · Ada  Rust has a different construct for creating arrays. One-Dimensional Arrays. Before we move to two-dimensional arrays, it is best to revisit one-dimensional arrays. Please check out How to Declare and Initialize an Array. Sample Codes. Consider the following codes.

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;

Rust - How to create Two Dimensional Array Example, Rust has a different construct for creating arrays. One-Dimensional Arrays. Before we move to two-dimensional arrays, it is best to revisit one-  There are two syntactic forms for creating an array: A list with each element, i.e., [x, y, z]. A repeat expression [x; N], which produces an array with N copies of x. The type of x must be Copy. Arrays of sizes from 0 to 32 (inclusive) implement the following traits if the element type allows it: Debug; IntoIterator (implemented for &[T; N] and &mut [T; N])

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
    let grid: &mut [&mut [_]] = grid_base.as_mut_slice();

    // Accessing data
    grid[0][0] = 4;
}

array2d - Rust, API documentation for the Rust `array2d` crate. Array2D provides a fixed sized two-dimensional array. An Array2D can be created in many different ways. Array elements are identified by a unique integer called the subscript/ index of the element. Populating the array elements is known as array initialization. Array element values can be updated or modified but cannot be deleted. Declaring and Initializing Arrays. Use the syntax given below to declare and initialize an array in Rust. Syntax

Initialization: There are several approaches for 2D Array initialization:

  1. Using constants for M (rows) & N (columns)

    const M: usize = 2;
    const N: usize = 4;
    
    let mut grid = [[0 as u8; N] ; M];
    
  2. Explicit declaration with type annotations

    let mut grid: [[u8; 4]; 2] = [[0; 4]; 2];
    

Traversing: The read-only traversing is as easy as:

for (i, row) in grid.iter().enumerate() {
    for (j, col) in row.iter().enumerate() {
        print!("{}", col);
    }
    println!()
}

or

for el in grid.iter().flat_map(|r| r.iter()) {
    println!("{}", el);
}

Updating element(s):

for (i, row) in grid.iter_mut().enumerate() {
    for (j, col) in row.iter_mut().enumerate() {
        col = 1;
    }
}

multiarray - Rust, As a side effect, it also supports one-dimensional arrays that have a stride other than one. array. One 2D view and one 1D view into part of the data is created. Arrays are created using brackets [], and their size, which is known at compile time, is part of their type signature [T; size]. Slices are similar to arrays, but their size is not known at compile time. Instead, a slice is a two-word object, the first word is a pointer to the data, and the second word is the length of the slice.

You can also create a 2D array like this (using Vec) if you don't have a known size at compile time:

let width = 4;
let height = 4;

let mut array = vec![vec![0; width]; height];

Use it like this:

array[2][2] = 5;

println!("{:?}", array);

Output:

0 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0

Available since rust 1.0.0 https://doc.rust-lang.org/std/vec/struct.Vec.html

2, 3, n dimensional arrays : rust, I'm in the early stages of creating an Image Editor, inspired by VIM. The goal I'm aiming towards is to be able to create thumbnails fast and easily. I document the​  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?

Multidimensional Arrays and Operations with NDArray, Get the Book on Data Analysis with Rust Notebooks or check out the Let's take a look at how we can create a two-dimensional ndarray Array  We demonstrated how to create arrays, find out their dimensionality, index them, and how to invoke some basic mathematical operations. Support this work You can access this notebook and more by getting the e-book on Data Analysis with Rust Notebooks .

Creating two dimensional arrays in Rust - arrays - php, How do I create an empty mutable two dimensional array in Rust? This is what I have tried so far: let mut state[[u8 * 4] * 4]; This produces the error error:  Arrays in Rust are fixed size, and Rust requires that every element in an array is initialized to a valid value when the array is initialized. The result of these requirements is array initialization in Rust is a much deeper topic than it would seem.

🤚 Creating two-dimensional arrays in Rust, Editor's Note: This answer precedes Rust 1.0, and some concepts and syntax have changed. Other answers relate to Rust 1.0. Do you want the contents of the​  You can create arrays by a regular square bracket enclosed list ([x, y, z, w]), or if you want an array prefilled with the same data, you can use ([x; n], where n is the length) Here's an example of using the [x, y, z] syntax for the outer array and both syntaxes for the inner one.

Comments
  • Yes. This works. Do you know how would I pass such array to the function? The function needs to change values of array. Thanks.
  • You could pass the value in two ways. One option would be &mut [[u8 * 4] * 4]--- pointer to a two-dimensional fixed length array. You would just do &mut state to get such a pointer.
  • Oh, and normally having a mutable variable like this would also allow you to mutate the elements of a fixed-length array, as they are owned by the variable. Unfortunately this bug <github.com/mozilla/rust/issues/3226> will prevent you for now.
  • @NikoMatsakis Thanks. I got it working like this & [mut [mut u8 * 4] * 4] for function parameter. How can I get pointer to first row of two dimensional array?
  • For future visitors: this is for a pre-1.0 version of rust, there's another answer below with an updated syntax. let mut state = [[0u8; 4]; 4];.
  • Note that this panics if you access out of bounds. Which doesn't feel very rust-like.
  • Thanks hardy, but "(and, yes, the mutability works now)" -> how would you access and mutate one element ?
  • @AndyHayden in the two years since your comment was posted bounds checking must have been properly implemented, as I receive compile time errors when attempting out-of-bounds access on both the outer and inner arrays.
  • I think it should read ...chunks_mut(height)... assuming access is grid[0...width-1][0...height-1]