How do I allocate an array at runtime in Rust?

13,648

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.

Share:
13,648
Admin
Author by

Admin

Updated on July 27, 2022

Comments

  • Admin
    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?