How do I allocate an array at runtime in Rust?

你说的曾经没有我的故事 提交于 2020-08-04 14:49:17

问题


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?


回答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 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();



回答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.



来源:https://stackoverflow.com/questions/34399277/how-do-i-allocate-an-array-at-runtime-in-rust

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!