1

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?

2 Answers 2

5

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];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, this makes sense. MAX_X and MAX_Y are constants, yes. Is it the Rustic way in general to prefer allocating default structures, then filling them with proper values later?
@descent: That's hugely subjective and depends on the specific case. Personally, I avoid having "dummy" values lying around, purely so I don't have to keep track of whether I've replaced them or not.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.