arrays - 具有包含引用的可能变体的枚举数组

标签 arrays enums rust

<分区>

我尝试编写战舰的纸质游戏,其中战场是一个枚举数组。我找不到初始化数组的方法。

enum Tile {
    Water,
    Debris,
    Ship(Rc<Ship>),
}

fn main() {
    let mut a = [[Tile::Water; 10]; 10]; //Tile::Water doesn't implement Copy (the compiler is dumb)
    let mut b: [[Tile; 10]; 10];
    for i in 1..10 {
        for j in 1..10 {
            b[i][j] = Tile::Water;
        }
    } //use of possibly uninitialized b (I'm trying to initialize it)
}

如何做到这一点?我不是为游戏寻找另一种解决方案,这只是这里的一个例子。

最佳答案

试试这个:

enum Tile {
    Water,
    Debris,
    Ship(Rc<Ship>),
}

impl Default for Tile {
    fn default() -> Self {
        Tile::Water
    }
}

fn main() {
    let mut b: [[Tile; 10]; 10] = Default::default();
}

关于arrays - 具有包含引用的可能变体的枚举数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55161524/

相关文章:

php - 使用 POST android 发送 php 数组

java - 将依赖值注入(inject)枚举

C# 枚举为 int

c++ - 让枚举值等同于许多其他值

rust - 如何用预定义的容量填充向量?

memory-management - Rust 会释放被覆盖变量的内存吗?

rust - 如何通过链接器-rlink参数?

c# - 并非所有代码路径都返回值错误

java - 练习 Java - EDX

arrays - 数组查询