I am from Java, I like using arrays in this manner.
public int do_something(int width, int height){
int[][] nums = new int[height][width];
return 1;
}
In the code above this isn't a problem and Java will create a 2D array of int
values and fill them with zeros.
I want to achieve this with Rust as well. This is what I tried.
fn do_something(n: usize, m: usize) -> i32 {
let memo: [[i32; m]; n] = [[0; m]; n];
1
}
The program wouldn't compile, it tells me that I cannot initialize arrays with non-constants. My problem is that I don't know the values of n and m beforehand.
I tried using a vector instead of arrays like this:
fn do_something(n: usize, m: usize) -> i32 {
let mut nums: Vec<Vec<i32>> = Vec::new();
for _i in 0..n{
let mut each: Vec<i32> = Vec::new();
for _j in 0..m{
each.push(0);
}
nums.push(each);
}
println!("{:?}", nums);
1
}
Is there a simpler approach to initializing arrays with variables and filling them with zeros? Or should I suffice myself with the above approach?
CodePudding user response:
Is there a simpler approach to initializing arrays with variables and filling them with zeros?
You can just convert the array literals (which require a compile-time length) to vec pseudo-literals, which don't:
fn do_something(n: usize, m: usize) -> i32 {
let memo = vec![vec![0i32; m]; n];
1
}
CodePudding user response:
If you need the values to have a runtime-defined, but fixed size (i.e. if they won't be resized after creation), you can strip one layer of indirection by using Box<[i32]>
instead of Vec<Vec<i32>>
:
fn do_something(n: usize, m: usize) -> i32 {
let memo: Box<[i32]> = vec![0; m * n].into_boxed_slice();
// and then access the values with e.g. `memo[x * m y]`
1
}