What's the best way to initialize large array?


#1

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 ?


How to initialize array in rust
#2

vec![0; 100000] works.


#3

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.


#4

[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.


#5

Cool. Thanks for your help !!


#6

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


#7

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.


#8

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


#9

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.