Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a Rust array length dynamically?

Tags:

arrays

rust

I want to create array like this:

let arr = [0; length]; 

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. 

Is it possible to create array with dynamic length? I want an array, not a Vec.

like image 544
Dima Kudosh Avatar asked Jan 08 '16 19:01

Dima Kudosh


People also ask

Can you dynamically increase array size?

You can't change the size of the array, but you don't need to. You can just allocate a new array that's larger, copy the values you want to keep, delete the original array, and change the member variable to point to the new array. Allocate a new[] array and store it in a temporary pointer.

Does rust have dynamic arrays?

No. By definition, arrays have a length defined at compile time.

Can the size of dynamic array be changed at run time?

Size of an array Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array. Still if you try to assign value to the element of the array beyond its size a run time exception will be generated.


2 Answers

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.

You will need to use a Vec:

let arr = vec![0; length]; 

See also:

  • Is it possible to control the size of an array using the type parameter of a generic?
like image 170
Shepmaster Avatar answered Sep 29 '22 09:09

Shepmaster


This should be possible after variable length arrays (VLA) are implemented.

like image 24
Aaron Zorel Avatar answered Sep 29 '22 11:09

Aaron Zorel