如何动态设置 Rust 数组长度? [英] How to set a Rust array length dynamically?

查看:37
本文介绍了如何动态设置 Rust 数组长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像这样创建数组:

let arr = [0; length];

其中长度是 usize.但是我收到这个错误

Where length is a usize. But I get this error

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? I want an array, not a Vec.

推荐答案

是否可以创建具有动态长度的数组?

Is it possible to create array with dynamic length?

没有.根据定义,数组的长度在编译时定义.一个变量(因为它可以变化)在编译时是未知的.编译器不知道要在堆栈上分配多少空间来为数组提供存储空间.

No. By definition, arrays have a length defined at compile time. A variable (because it can vary) is not known at compile time. The compiler would not know how much space to allocate on the stack to provide storage for the array.

您将需要使用 Vec:

You will need to use a Vec:

let arr = vec![0; length];

另见:

这篇关于如何动态设置 Rust 数组长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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