拥有此
#[derive(Debug, PartialEq, Default)]
pub enum CellContent {
Move(Symbol),
#[default]
Empty,
}
pub struct Game {
pub table: [[CellContent; 3]; 3],
}
我怎样才能缩短这个?
pub fn new() -> Game {
Game {
table: [
[
CellContent::default(),
CellContent::default(),
CellContent::default(),
],
[
CellContent::default(),
CellContent::default(),
CellContent::default(),
],
[
CellContent::default(),
CellContent::default(),
CellContent::default(),
],
],
}
}
|请回答,指给我锈书页面或其他官方文件
注意:我不是在寻找一些高级技巧,但只是语法糖,如果有
当数组元素的类型实现Default
时,数组类型本身也会实现,因此您可以使用Default::default()
:填充table
pub fn new() -> Game {
Game {
table: Default::default(),
}
}
这将使用Default
来获得嵌套数组的初始值,进而使用CellContent
的Default
实现来获得每个嵌套数组元素的初始值。
如果您的类型CellContent
派生Copy
,那么您也可以使用数组元素的复制初始化;语法[x; N]
创建N
元素的数组,复制x
以填充所有N
元素:
pub fn new() -> Game {
Game {
table: [[CellContent::default(); 3]; 3],
}
}