degs
degs

Reputation: 1072

Cannot give struct as a type to create a 2D array of structs

I'm attempting to create a simple, fixed-size 2D array of Node structs with size [MAX_X, MAX_Y]. This:

let mut map = [[Node; MAX_X as usize]; MAX_Y as usize];

struct Node {
    x: i32,
    y: i32,
}

gives the error message:

main.rs:12:21: 12:25 error: `Node` is a struct variant name, but this expression uses it like a function name [E0423]
main.rs:12     let mut map = [[Node; MAX_X as usize]; MAX_Y as usize];
                               ^~~~
main.rs:12:21: 12:25 help: did you mean to write: `Node { /* fields */ }`?

What am I missing?

Upvotes: 1

Views: 758

Answers (2)

tafia
tafia

Reputation: 1562

let mut map = [[Node; MAX_X as usize]; MAX_Y as usize];

There are 2 issues

  • In rust : is used to define the variable type and = to define its value. In your case you used = to define a type

  • All variables need to be initialized (memory should be allocated).

    • If MAX_X and MAX_Y values are dynamic then you don't have a choice but use Vec<_> instead of fixed-sized array

    • If MAX_X and MAX_Y are constants then you can statically initialize map like this (note that data type is inferred): let mut map = [[Node {x:0, y:0}, Node {x:0, y:0}, Node {x:0, y:0}], [Node {x:0, y:0}, Node {x:0, y:0}, Node {x:0, y:0}], [Node {x:0, y:0}, Node {x:0, y:0}, Node {x:0, y:0}]]

Upvotes: 1

DK.
DK.

Reputation: 58975

This is vaguely akin to saying let mut i = i32;; it doesn't make any sense because you're trying to assign a type to a variable. You need to actually provide a value, not a type.

However, even that won't work because, given the definition above, Node isn't Copy, so the compiler can't construct the array anyway.

Here's something that will work, but first, a few notes:

  • Note that this is constructing the array on the stack. If you make it too big, you run the risk of overflowing the stack and crashing.

  • MAX_X and MAX_Y must be constants; they cannot be variables. Your casting of them (and lack of a complete example) makes me worry that you might be using variables..

fn main() {
    #[derive(Copy, Clone)]
    struct Node {
        x: i32,
        y: i32,
    }

    const MAX_X: usize = 8;
    const MAX_Y: usize = 16;

    let mut map = [[Node { x: 0, y: 0 }; MAX_X]; MAX_Y];
}

Upvotes: 5

Related Questions