我想创建这样的数组:
let arr = [0; length];
其中长度是一个usize
。但是我得到了这个错误
E0307
The length of an array is part of its type. For this reason, this length
must be a compile-time constant.
是否可以创建具有动态长度的数组?我想要一个数组,而不是 Vec
。
最佳答案
Is it possible to create array with dynamic length?
没有。根据定义,数组的长度在编译时定义。变量(因为它可以变化)在编译时是未知的。编译器不知道要在堆栈上分配多少空间来为数组提供存储空间。
您将需要使用 Vec
:
let arr = vec![0; length];
另见:
关于arrays - 如何动态设置 Rust 数组长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39088095/