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

4 memory allocation dynamic rust

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

就像在C++中一样:

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

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

DK.*_*DK. 10

根据您的问题,如果您还没有这样做,我建议您阅读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();
Run Code Online (Sandbox Code Playgroud)

  • 这个问题要求一个数组并提供C++等价物作为一个例子,而这个答案涵盖了动态集合类型.这也是前两个用于分配生锈阵列的谷歌结果,但我不认为这回答了这个问题. (3认同)
  • @Score_Under:除了 C++ 代码使用动态分配的数组,所以几乎没有实际区别。直接翻译是不安全和单调的。此外,考虑到最初的提问者接受了给出的答案,我会说它*确实*回答了他们打算提出的问题。 (2认同)
  • 问题中的数组是在运行时分配的,否则它是一个固定数组(不能调整大小、追加等)。Rust 确实有一个等效的类型,它是一些标准库函数所必需的(例如,从文件中批量读取时)。 (2认同)
  • @Score_Under 这是一个切片,而不是您所指的函数中的数组 `fn read(&amp;mut self, buf: &amp;mut [u8]) -&gt; Result&lt;usize&gt;` (2认同)

Inf*_*her 5

完全有可能在堆上分配一个固定大小的数组:

let a = Box::new([0.0f64; 1000]);
Run Code Online (Sandbox Code Playgroud)

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

for i in 0..1000 {
    a[i] = i as f64;
}
Run Code Online (Sandbox Code Playgroud)

您可以通过以下操作手动释放它:

std::mem::drop(a);
Run Code Online (Sandbox Code Playgroud)

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.

  • 另请参阅[是否可以在 Rust 中使用运行时确定大小的堆栈分配数组?](/sf/ask/1950187571/);[将数组分配到运行时已知大小的堆上](/sf/ask/2919766671/);[有没有办法直接在堆上分配标准 Rust 数组,完全跳过堆栈?](/sf/ask/3758370871/); [在 Rust 堆上创建固定大小的数组](/sf/ask/1806362211/);[Rust 1.0中如何在堆上分配数组?](/sf/ask/2116993931/)等 (2认同)