0

I tried coding the paper game of battleships, where a battlefield is an enum array. I couldn't find a way to initialize the array.

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)
}

How can this be done? I am not looking for another solution for the game, it is just an example here.

hellow
  • 12,430
  • 7
  • 56
  • 79
Tesik
  • 68
  • 5
  • 2
    Possible duplicate of https://stackoverflow.com/questions/49388285/is-there-a-more-idiomatic-way-to-initialize-an-array-with-random-numbers-than-a https://stackoverflow.com/questions/31360993/what-is-the-proper-way-to-initialize-a-fixed-length-array https://stackoverflow.com/questions/31360993/what-is-the-proper-way-to-initialize-a-fixed-length-array and https://stackoverflow.com/questions/55143009/is-it-possible-to-declare-an-immutable-array-and-assign-value-to-its-elements-se – hellow Mar 14 '19 at 11:49
  • 3
    *"the compiler is dumb"* nah.. it's not. It has valid reasons to not let that happen. – hellow Mar 14 '19 at 11:50
  • @hellow Two of those links are to the same question. – trent Mar 14 '19 at 11:54
  • @hellow No, the compiler is truly dumb in this case. It has no good reason to not allow `[Tile::Water; 10]` and in fact it should eventually be allowed (https://github.com/rust-lang/rust/issues/49147). – Centril Mar 17 '19 at 05:51

1 Answers1

-1

Try this:

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();
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
vkurchatkin
  • 13,364
  • 2
  • 47
  • 55
  • 4
    How is your answer different from the suggested duplicate: https://stackoverflow.com/questions/28656387/initialize-a-large-fixed-size-array-with-non-copy-types – hellow Mar 14 '19 at 12:02
  • @hellow The suggested question asks for non-Copy types generally. Non-Copy types usually have a good reason not to be copied "as-is" but an enum with only some variants which hold a reference is a specific case where, in many cases, copying is safe. That is not to say such enums should implement Copy. The compiler does not analyze, whether the value in question can be safely copied and straight out assumes it cannot. I asked for a work-around in this specific case. – Tesik Mar 15 '19 at 22:59