如何在Rust 1.0中在堆上分配数组? [英] How to allocate arrays on the heap in Rust 1.0?
问题描述
已经有一个问题为此,但与Rust 0.13有关,语法似乎已更改.从当前的文档可以理解在堆上创建数组将是这样的:
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
我在做什么错了?
推荐答案
问题是该数组作为参数传递给Box::new
函数,这意味着必须先创建 ,这意味着必须在堆栈上创建.
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.
您要的是编译器在堆栈上创建 8兆字节数据:这就是溢出的原因.
You're asking the compiler to create 8 megabytes of data on the stack: that's what's overflowing it.
解决方案是根本不使用固定大小的数组,而是使用Vec
.我想到的最简单的方法是使Vec
达到800万10.0
:
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();
}
此应该仅执行一次堆分配.
Note that you can subsequently take a Vec
and turn it into a Box<[_]>
by using the into_boxed_slice
method.
另请参阅:
这篇关于如何在Rust 1.0中在堆上分配数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!