How to allocate arrays on the heap in Rust 1.0?

2019-01-08 00:59发布

There is already a question for this but related to Rust 0.13 and the syntax seems to have changed. From the current documentation I understood that creating an array on the heap would be something like this:

fn main() {
    const SIZE: usize = 1024 * 1024;
    Box::new([10.0; SIZE]);
}

But when I run this program I get the following error:

thread '<main>' has overflowed its stack

What am I doing wrong?

标签: arrays heap rust
1条回答
等我变得足够好
2楼-- · 2019-01-08 01:18

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:

查看更多
登录 后发表回答