Hi every one.
I am new to Rust (like today-new), and since the document for this language is relatively little, I couldn't find what I am looking for, at least not easily.
I have a struct called Node that have special characteristic (say "Color") that I want to be mutable.
struct Node {
R: i32,
G: i32,
B: i32,
}
As it's a node, it should have some coordinate, which I will denote using a 2D array. Therefore, I want to create a 2D array (say maybe with width 200 and height 300) called B of this Node struct. So accessing and modifying a node could be done simply B[0][0].B=69 or something like that. (sorry, can't help it)
Since this might be a common question for future reference if the language blow up, I just want some good details:
- What is the shortest and most simple syntax to achieve this task.
- Assuming I do not want to create an array, but rather a vector for future expansion, what cloud be a simple syntax for this?
- I did some reading and it seems that creating a 2D vector will potentially consume computer resources a lot. Is that true? Does that mean, in general, I should use an array if I am pretty positive that my data size wouldn't change, or use 1D vector with a length equal to width*height instead? Basically what is the optimal solution to handle 2D data problem like I just mention.
EDIT:
Copy/Pasted the Solution from idkravitz for convenience.
#![feature(new_uninit)] // required for "option 2"
#[derive(Copy,Clone,Debug)] // Debug here is just for printing
struct Node {
r: i32,
g: i32,
b: i32,
}
fn main() {
// option 1
let arr = Box::new([[Node { r: 0, g: 0, b: 0}; 300]; 200]);
println!("{:?}", arr[5][1]);
// option 1' (with nightly and unsafe, won't cause SO on large sizes)
// but it's generally not recommended especially for complex types
let arr = Box::new_zeroed();
let arr: Box<[[Node; 300]; 200]> = unsafe { arr.assume_init() };
println!("{:?}", arr[5][1]);
// option 2 with vec
let arr = vec![[Node{r: 42, g: 42, b: 42}; 300]; 200];
println!("{:?}", arr[5][1]);
// option 3 with vec and linear indexing
let (width, height) = (200, 300);
let arr = vec![Node{r:10, g: 20, b: 30}; width*height];
println!("{:?}", arr[5 * width + 1]); // corresponds to arr[5][1]
}