What's the best way to initialize large array?

For Example : I want an array of 100000 elements. But if we use [0; 100000] it will definitely give me stack overflow error because fixed arrays are allocated in stack as far as I know in rust.

So what's the best way to create an array of 100000 in rust ?

1 Like

vec![0; 100000] works.

2 Likes

You can use boxed array.

let x = box [1.1f64; 10000000];

It only works in Nightly at the moment. In stable Rust you can make a vector, then unsafely cast it into a boxed array.

1 Like

[quote="anmej, post:3, topic:3458"]
In stable Rust you can make a vector, then unsafely cast it into a boxed array.
[/quote]into_boxed_slice is safe.

3 Likes

Cool. Thanks for your help !!

Can you explain it why we can use vector to initialize large array?

When you crate an (unboxed) array it will be put on the stack. The stack does not have much memory though. When you box the array or use a vector, the memory will be allocated on the heap which is much larger.

2 Likes

You can't. Using a vec is a different approach that is often, but not always, interchangeable.

1 Like

Another way is

Vec::with_capacity(100_000)

This Vec has a length of 0 at first, but when it grows, it doesn't need to re-allocate.