Search code examples
memorydynamicrustallocation

How do I allocate an array at runtime in Rust?


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?


Solution

  • 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();