arraysvectormultidimensional-arrayrust

Creating two dimensional arrays in Rust


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

Solution

  • 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.