如何在堆上分配阵列位于Rust 1.0(测试版)? [英] How to allocate arrays on the heap in Rust 1.0 (beta)?
问题描述
有已经是<一个href=\"http://stackoverflow.com/questions/26637158/stack-overflow-with-large-fixed-size-array-in-rust-0-13\">question为此但是相关生锈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
我在做什么错了?
What am I doing wrong?
推荐答案
的问题是,该数组被传递到箱::新
函数作为参数,这意味着它必须创建的第一个的,这意味着它已经被创建的堆栈的
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:
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.
修改:另外请注意,随后就可以采取 VEC
键,把它变成一个盒&LT; _] &GT;
通过使用<$c$c>into_boxed_slice$c$c>方法。
Edit: Also 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屋!