Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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],
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading