在运行时以已知大小将数组分配到堆上 [英] Allocate array onto heap with size known at runtime

查看:78
本文介绍了在运行时以已知大小将数组分配到堆上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,我可以像这样将1000个int的数组放到堆上:

In C++, I could put an array of 1000 ints onto the heap like this:

int size = 1000;
int* values = new int[size];
delete[] values;

我不知道如何在Rust中做同样的事情.

I can't figure out how to do the equivalent in Rust.

let size = 1000;
let values = Box::new([0; size]) // error: non-constant path in constant expression

据我了解,Rust强制在编译时知道所有数组的大小,并且不允许您在创建数组时使用表达式.

To my understanding, Rust forces the size of all arrays to be known at compile time and doesn't let you use expressions when creating arrays.

推荐答案

Rust中的数组是固定长度的.如果要使用动态大小的数组,请使用Vec.在这种情况下,最简单的方法是使用 vec! 宏:

Arrays in Rust are fixed-length. If you want a dynamically-sized array, use Vec. In this case, the simplest way is with the vec! macro:

let size = 1000;
let values = vec![0; size];

此外,如果您 super 担心Vec长三个单词,并且在创建存储后不需要调整存储大小,则可以显式丢弃内部容量,并添加values最多减少两个单词:

Also, if you're super concerned about Vec being three words long and don't need to resize the storage after it's created, you can explicitly discard the internal capacity, and bring values down to two words on the stack:

let values = values.into_boxed_slice(); // returns a Box<[i32]>.

这篇关于在运行时以已知大小将数组分配到堆上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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