realtebo
realtebo

Reputation: 25691

Is there a shortcut syntax to initialize an array with defaults?

Having this

#[derive(Debug, PartialEq, Default)]
pub enum CellContent {
    Move(Symbol),
    #[default]
    Empty,
}

pub struct Game {
    pub table: [[CellContent; 3]; 3],
}

How can I short this ?

pub fn new() -> Game {
    Game {
        table: [
            [
                CellContent::default(),
                CellContent::default(),
                CellContent::default(),
            ],
            [
                CellContent::default(),
                CellContent::default(),
                CellContent::default(),
            ],
            [
                CellContent::default(),
                CellContent::default(),
                CellContent::default(),
            ],
        ],
    }
}

| Please, answering, point me to rust book page or other official documentation

NOTE: I am not looking for some advanced trick, but only to syntax sugar, if any

Upvotes: 0

Views: 195

Answers (1)

cdhowie
cdhowie

Reputation: 169256

When the type of an array element implements Default, the array type itself does as well, so you can just populate table with Default::default():

pub fn new() -> Game {
    Game {
        table: Default::default(),
    }
}

This will use Default to obtain the initial value for the nested arrays, which will in turn use the Default implementation of CellContent to obtain the initial value for each nested array element.

If your type CellContent derives Copy then you could also use copy-initialization of array elements; the syntax [x; N] creates an array of N elements, copying x to fill all N elements:

pub fn new() -> Game {
    Game {
        table: [[CellContent::default(); 3]; 3],
    }
}

Upvotes: 3

Related Questions