Home > Back-end >  Creating several arrays of different but fixed sizes
Creating several arrays of different but fixed sizes

Time:09-15

Is it possible to create arrays of a technically variable size but that is known at compile time ? More precisely, I want to do something like this :

fn main() {
    for n in 1..5 {
        let array: [i32; n] = [0; n];
        // Do stuff with array
    }
}

This code does not compile, but i feel like it should be possible to do, since the only thing the for loop could be unraveled by the compiler, like this :

fn main() {
    let array: [i32; 1] = [0; 1];
    let array: [i32; 2] = [0; 2];
    let array: [i32; 3] = [0; 3];
    let array: [i32; 4] = [0; 4];
    let array: [i32; 5] = [0; 5];
}

which compiles and does what I want, but is very repetitive

I could use vectors or other data structures, but then I would have variables in the heap, and I don't think that I should use the heap just because i use my arrays in a for loop

CodePudding user response:

Just use the unroll crate.

#[unroll::unroll_for_loops]
fn main() {
    for n in 1..5 {
        let array: [i32; n] = [0; n];
        println!("{:?}", array);
    }
}

CodePudding user response:

The compiler is looking for a constant when specifying array size. Since n is variable, it has issue. You are still wanting a variable-sized array, which I believe would need to be allocated on the heap if you're using standard types.

In unstable Rust, there is a feature called "unsized_locals", which can be enabled to provide a variable-sized array allocated on the stack, but this is not yet implemented in the stable version of the language.

There is also a crate called "heapless" that does what you're looking for.

  • Related