将数组分配到运行时已知大小的堆上

问题描述 投票:0回答:4

在 C++ 中,我可以像这样将 1000 个

int
s 的数组放到堆上:

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

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

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

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

arrays rust heap-memory
4个回答
33
投票

Rust 中的数组是固定长度的。如果你想要一个动态大小的数组,使用

Vec
。在这种情况下,最简单的方法是使用
vec!
宏:

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

另外,如果你 超级 担心

Vec
是三个字长并且不需要在创建后调整存储大小,你可以显式丢弃内部容量,并将
values
减少到两个字堆栈:

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

2
投票

Rust 的堆分配数组是

std::Vec
。在引擎盖下它只是一个数组(阅读文档中的§Guaranteeshttps://doc.rust-lang.org/std/vec/struct.Vec.html#guarantees

分配未初始化的内存使用

Vec::with_capacity()
。然后根据需要
push()
值:

// preallocate the vector capacity
let mut values = Vec::<i32>::with_capacity(1000);

// fill the vector with values
for i in 0..1000 {
    values.push(i);
}

// downgrade into a boxed slice
let mut values = values.into_boxed_slice();

0
投票

如果你想要堆上的数组(例如

Box<[u8; 100]>
)而不是切片(例如
Box<[u8]>
)那么从Rust 1.66开始你可以使用Box的
TryFrom<Vec<T>>
从与数组大小相同的Vec转换.如果容量也匹配,则没有副本。

let array_on_heap: Box<[u8; 1000]> = vec![0_u8; 1000].try_into().unwrap();

-2
投票

如果数组的大小可以在编译时确定*,您可以使用这样的常量:

const size: usize = 1000; // or: = some_const_fn() 
let values = Box::new([0; size])

* 由于 Rust 1.46 控制流和循环在

const fn
中得到支持。

© www.soinside.com 2019 - 2024. All rights reserved.