Elegantly/conveniantly filling arrays


#1

Hi, I’m still a rookie, so please excuse if this is a case of DNRM.
I am trying to build a chessboard by defining a 2x2 array of `enum Field(Figure, Empty).
When I first try to fill it the compiler complained that I did not initialize it corretly. However I don’t find a way to initialize it other than actually writing it out manually. All the examples in the doc only cover arrays of primitive types or up to 5 elements.
I hoped (coming from ruby) there would be some sort of sugar like

   let mut board: [Field; 8] = 
     for row in 0..8 {
         for col in 0..8 {
             Field::Empty;
         }
     } 

but that was wishful thinking :stuck_out_tongue_closed_eyes:

How do I do this other than reverting to using a vector?

Thank you


#2

In your particular case, you’re lucky, because you’re initializing your board array with a single element, repeated 8 times. You can achieve it as follows:

#[derive(Clone, Copy)]
enum Field {
    Empty,
    Full(i32),
}

fn main() {
   let mut board: [Field; 8] = [Field::Empty; 8];
}

If you wanted to store different elements, depending on the index for example, you would be out of luck: see the problem and some alternatives at http://stackoverflow.com/questions/26757355/how-do-i-collect-into-an-array.


#3

Thank you, but that means that I still have to implement the trait core::marker::Copy for Field myself right?
At least the compiler complained about it:

error: the trait core::marker::Copy is not implemented for the type Field


#4

Yep; as you can see, an easy way is to let the compiler write it itself with

#[derive(Clone, Copy)]

I provided it in my example above, which compiles: http://is.gd/bIQlH9. (I put Clone there as well because a Copy type is required to be also Clone.)


#5

Oops, I wrote a lower case clone and copy, which is why the compiler complained.
Ok, everything is solved. Thank you.


#6

All right, you’re welcome :slight_smile:


#7

If you want a doubly-nested array, then check out http://is.gd/t7vSuQ. It’s almost the exact same code. I also added Debug to the derive so you could see how to print out the board.


#8

Thank you, this is basically what I did. Next step would be to implement a custom trait display for Field.