Reputation: 197
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
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.
The advantage of using Default
over writing a constructor (as in Angelicos' answer) is that:
derive
to implement itderive
..Default::default()
struct update syntax to specify some fields of a struct, while defaulting the rest.See also:
Upvotes: 1
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