Search code examples
arraysrustinitialization

How do I initialize an array of numbers with a variable?


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?


Solution

  • 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
    }