How to allocate arrays on the heap in Rust 1.0?

The problem is that the array is being passed to the Box::new function as an argument, which means it has to be created first, which means it has to be created on the stack.

You’re asking the compiler to create 8 megabytes of data on the stack: that’s what’s overflowing it.

The solution is to not use a fixed-size array at all, but a Vec. The simplest way I can think of to make a Vec of 8 million 10.0 is this:

fn main() {
    const SIZE: usize = 1024 * 1024;
    let v = vec![10.0; SIZE];
}

Or, if for some reason you’d rather use iterators:

use std::iter::repeat;

fn main() {
    const SIZE: usize = 1024 * 1024;
    let v: Vec<_> = repeat(10.0).take(SIZE).collect();
}

This should only perform a single heap allocation.

Note that you can subsequently take a Vec and turn it into a Box<[_]> by using the into_boxed_slice method.

See also:

Leave a Comment