You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中是否有语法糖可快速初始化默认值数组?

问题:简化Rust中Game结构体的new函数写法

现有代码如下:

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

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

如何简化以下new函数的写法?

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

注:仅需语法糖,不需要高级技巧。


简化方案

方案1:简化数组初始化语法

利用Rust固定长度数组的默认初始化语法,直接嵌套生成二维数组:

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

方案2:为Game派生Default trait

先给Game结构体派生Default(因为其字段table的类型[[CellContent;3];3]已实现Default):

#[derive(Debug, Default)]
pub struct Game {
    pub table: [[CellContent; 3]; 3],
}

此时new函数可以简化为:

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

语法依据

Rust中,当元素类型实现了Default trait时,固定长度数组会自动实现Default,因此可以通过[T::default(); N]快速初始化指定长度的数组,二维数组可嵌套使用该语法。若结构体的所有字段均实现Default,可为结构体派生Default trait,直接调用StructName::default()生成默认实例。

内容的提问来源于stack exchange,提问作者realtebo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 04:36:18