Nicke7117
Nicke7117

Reputation: 197

How to initialize an array in a struct definition?

How can I set the array values to 0 in this struct? This is obviously wrong. How do I do it correctly?

struct Game {
    board: [[i32; 3]; 3] = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
}

In a function this would have been:

let board: [[i32; 3]; 3] = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];

Upvotes: 3

Views: 2086

Answers (2)

harmic
harmic

Reputation: 30587

If you want to define a default value for a struct, you can implement the Default trait for it.

In the case of a struct containing values that themselves implement Default, it is as simple as adding #[derive(Default)]:

#[derive(Default,Debug)]
struct  Game {
    board: [[i32; 3]; 3]
}


fn main() {
    let game : Game = Default::default();
    println!("{:?}", game);
}

Alternatively, if your struct is more complex, you can implement Default by hand.

Playground

The advantage of using Default over writing a constructor (as in Angelicos' answer) is that:

  1. You can use derive to implement it
  2. Data structures which contain your struct can also use derive
  3. You can use the ..Default::default() struct update syntax to specify some fields of a struct, while defaulting the rest.

See also:

Upvotes: 1

Angelicos Phosphoros
Angelicos Phosphoros

Reputation: 3057

You cannot initialize fields in struct definition because it is behaviour while struct must contain only data.

This should work:

struct  Game {
    board: [[i32; 3]; 3]
}

impl Game{
   fn new()->Self{
      Self{
        board: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
      }
   }
}

...
let game = Game::new();

Upvotes: 3

Related Questions