3

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]];
3
  • 1
    Are you trying to set a default value when the struct is initialized? Normally you'd have a constructor function to create the struct with the right defaults. Commented Nov 10, 2021 at 21:03
  • Yes, so the board will always be the same when initialized, and later on the values will be changed. @loganfsmyth Commented Nov 10, 2021 at 21:07
  • It is not clear what you're trying to achieve. Do you want to avoid writing this code again and again? Use a constructor (use it anyway). Do you want to avoid it completely, for some reason (for example, it is more than 3 items and it is verbose)? You can use Default::default() for default values (0 for integers) or array initialization syntax for any other constant value ([[0; 3]; 3]) Commented Nov 11, 2021 at 0:41

2 Answers 2

3

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

Comments

1

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:

2 Comments

The common pattern is to have both Default and new() in libraries. For apps, I tend to have only Default but this is opinion-based
3 is possible with new as well: S{f1, f2, ..S::new()}. Actually, you can use any expression which returns this struct.

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.