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

查看:1498
本文介绍了如何动态设置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天全站免登陆