如何在 Rust 1.0 的堆上分配数组? [英] How to allocate arrays on the heap in Rust 1.0?

查看:75
本文介绍了如何在 Rust 1.0 的堆上分配数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经有一个问题 为此,但与 Rust 0.13 相关,并且语法似乎已更改.从当前的 documentation 我明白在堆上创建一个数组将是这样的:

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 函数,这意味着它必须是创建 first,这意味着它必须在堆栈上创建.

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 MB 数据:这就是溢出的原因.

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();
}

应该只执行单个堆分配.

请注意,您随后可以使用 into_boxed_slice 方法.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆