如何在Rust中运行时分配数组?

问题描述 投票:4回答:2

一旦我分配了阵列,我该如何手动释放它?指针算法在不安全模式下是否可行?

就像在C ++中一样:

double *A=new double[1000];
double *p=A;
int i;
for(i=0; i<1000; i++)
{
     *p=(double)i;
      p++;
}
delete[] A;

Rust中有任何等效的代码吗?

memory dynamic rust allocation
2个回答
9
投票

根据你的问题,如果你还没有这样做,我建议你阅读Rust Book。 Idiomatic Rust几乎从不涉及手动释放内存。

至于动态数组的等价物,你需要Vector。除非你做一些不寻常的事情,否则你应该避免在Rust中使用指针算法。您可以将上述代码编写为:

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

1
投票

完全可以在堆上分配固定大小的数组:

let a = Box::new([0.0f64; 1000]);

由于deref强制,您仍然可以将其用作数组:

for i in 0..1000 {
    a[i] = i as f64;
}

你可以通过以下方式手动释放它:

std::mem::drop(a);

drop拥有阵列的所有权,所以这是完全安全的。正如在另一个答案中所提到的,几乎没有必要这样做,当它超出范围时,该框将被自动释放。

© www.soinside.com 2019 - 2024. All rights reserved.