12
votes

In C++, I could put an array of 1000 ints onto the heap like this:

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

I can't figure out how to do the equivalent in Rust.

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

To my understanding, Rust forces the size of all arrays to be known at compile time and doesn't let you use expressions when creating arrays.

2
See also Creating a fixed-size array on heap in Rust, How to allocate arrays on the heap in Rust 1.0 (beta)? or The Rust Programming Language chapter on vectors. I'd highly recommend reading the book as it covers many of these introductory topics.Shepmaster

2 Answers

26
votes

Arrays in Rust are fixed-length. If you want a dynamically-sized array, use Vec. In this case, the simplest way is with the vec! macro:

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

Also, if you're super concerned about Vec being three words long and don't need to resize the storage after it's created, you can explicitly discard the internal capacity, and bring values down to two words on the stack:

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

In case that the size of the array can be determined at compile time*, you can use a constant like this:

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

* Since Rust 1.46 control flows and loops are supported in const fn.