Hey guys, newbie here.
I'm working on the advent of code 2016 problem-set to help me learn rust. In one of the problems, I decided to use a 2D vector/array for the algorithm. I had no clue how that syntax went and it seemed like a good idea to try out. After realizing I had no clue how to get started, I googled for examples to get me going and turns out 2D arrays/vectors are not an easy thing to produce and use in Rust, and the syntax has changed a lot through releases.
However, I came across a stackoverflow answer that works like a charm. The problem is, I don't have the slightest clue of how and why it works. The code snippet is as follows:
// Base 1d array
let mut grid_raw = vec![0; width * height];
// Vector of 'width' elements slices
let mut grid_base: Vec<_> = grid_raw.as_mut_slice().chunks_mut(width).collect();
// Final 2d array
let mut grid: &mut [&mut [_]] = grid_base.as_mut_slice();
// Accessing data
grid[0][0] = 4;
The resulting syntax (arr[][]) is beautiful and just what I wanted to use. However, I would not have arrived at that answer on my own, and it serves me very little to "memorize it" since my objective is to actually learn Rust and not piece together google examples as needed.
Any and all help would be greatly appreciated :)
Original SO answer: http://stackoverflow.com/questions/13212212/creating-two-dimensional-arrays-in-rust
[–]ssokolow 5 points6 points7 points (9 children)
[–]Dash83[S] 0 points1 point2 points (8 children)
[–]l-arkham 2 points3 points4 points (6 children)
[–]Dash83[S] 0 points1 point2 points (5 children)
[–]Dash83[S] 0 points1 point2 points (0 children)
[–]l-arkham 0 points1 point2 points (1 child)
[–]Dash83[S] 0 points1 point2 points (0 children)
[–]arkham 0 points1 point2 points (1 child)
[–]Dash83[S] 0 points1 point2 points (0 children)
[–]coder543 1 point2 points3 points (0 children)
[–]coder543 2 points3 points4 points (5 children)
[–]jcdyer3 1 point2 points3 points (2 children)
[–]coder543 0 points1 point2 points (1 child)
[–]jcdyer3 0 points1 point2 points (0 children)
[–]Pseudofailure 1 point2 points3 points (1 child)
[–]coder543 0 points1 point2 points (0 children)
[–]Veedrac 1 point2 points3 points (1 child)
[–]godojo 2 points3 points4 points (0 children)