How do I allocate an array at runtime in Rust?
Solution 1
Based on your question, I'd recommend reading the Rust Book if you haven't done so already. Idiomatic Rust will almost never involve manually freeing memory.
As for the equivalent to a dynamic array, you want a vector. Unless you're doing something unusual, you should avoid pointer arithmetic in Rust. You can write the above code variously as:
// Pre-allocate space, then fill it.
let mut a = Vec::with_capacity(1000);
for i in 0..1000 {
a.push(i as f64);
}
// Allocate and initialise, then overwrite
let mut a = vec![0.0f64; 1000];
for i in 0..1000 {
a[i] = i as f64;
}
// Construct directly from iterator.
let a: Vec<f64> = (0..1000).map(|n| n as f64).collect();
Solution 2
It is completely possible to allocate a fixed-sized array on the heap:
let a = Box::new([0.0f64; 1000]);
Because of deref coercion, you can still use this as an array:
for i in 0..1000 {
a[i] = i as f64;
}
You can manually free it by doing:
std::mem::drop(a);
drop
takes ownership of the array, so this is completely safe. As mentioned in the other answer, it is almost never necessary to do this, the box will be freed automatically when it goes out of scope.
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Admin
Updated on July 27, 2022Comments
-
Admin almost 2 years
Once I have allocated the array, how do I manually free it? Is pointer arithmetic possible in unsafe mode?
Like in C++:
double *A=new double[1000]; double *p=A; int i; for(i=0; i<1000; i++) { *p=(double)i; p++; } delete[] A;
Is there any equivalent code in Rust?