How to initialize this array of arrays inside a structure?

I'm trying to find out the rust from a textbook. I thought playing Conway would be a good starting point.

I am having trouble understanding how to write this Grid :: new () fn.

Here is what I still have:

enum Cell { alive, dead } impl Cell { fn new() -> Cell { alive } struct Grid { priv inner: [ [Cell, .. GRID_SIZE], .. GRID_SIZE], } impl Grid { fn new() { Grid { inner: ???? } } } 

...

 fn main () { let grid = Grid::new(); // Stack allocated grid (internal stack allocad array) } 

I want the grid to be initialized with cells, all meaning live.

+6
source share
1 answer

Grid::new should initialize Grid::inner with a fixed-size array nested literal that is written exactly the same as the type, but with the value you want to initialize with your array instead of the Cell type:

 impl Grid { fn new -> Grid { Grid { inner: [[alive, ..GRID_SIZE], ..GRID_SIZE] } } } 

(You can use Cell::new() instead of alive if you prefer to use the constructor function.)

Then the inner member can be used in expressions (note that priv controls the visibility for code outside the current module):

 let grid = Grid::new(); let nested_fixed_sized_array: [[Cell, ..GRID_SIZE], ..GRID_SIZE] = grid.inner; let fixed_sized_array: [Cell, ..GRID_SIZE] = grid.inner[0]; let cell_element: Cell = grid.inner[0][0]; 

In Rust, nested arrays used in this example are a special case of fixed-size arrays. To find out how this works, see the Vectors and Strings section. In particular, unlike vectors (of type ~[T] ), which are dynamically allocated on the heap and can change their length (if they are mutable), fixed size arrays have a length built into the type ( [T, ..LENGTH] ), so that they cannot resize after creation. T itself must be either a fixed size type or a pointer. However, instead, fixed-size arrays are types of values ​​that can be directly distributed on the stack, built-in to struct definitions (for example, Grid ), etc.

Since a fixed-size array is itself a fixed-size type, a fixed-size nested array is just a special case when a fixed-size array is a type of element of a fixed-size array. In particular, the memory occupied by Grid::inner is exactly equal to GRID_SIZE * GRID_SIZE * sizeof(Cell) (if we ignore alignment). A fixed size vector of arrays ~[T, ..LENGTH] is also useful when you know the number of columns in a matrix, but not the number of rows.

Both vectors and fixed size arrays can serve as an argument to a function if the argument is a slice (type &[T] ).

Some details may change between now and the release of Rust 1.0. If you're interested, the Rust subreddit search for “dynamic-sized types” should include suggested changes and arguments behind them, or you can always ask for Reddit or the #rust IRC channel.

+8
source

All Articles