简体   繁体   English

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

[英]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++:就像在 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? Rust 中是否有任何等效代码?

Based on your question, I'd recommend reading the Rust Book if you haven't done so already.根据您的问题,如果您还没有阅读Rust Book ,我建议您阅读。 Idiomatic Rust will almost never involve manually freeing memory.惯用的 Rust 几乎从不涉及手动释放内存。

As for the equivalent to a dynamic array, you want a vector .至于等效于动态数组,您需要一个 vector Unless you're doing something unusual, you should avoid pointer arithmetic in Rust.除非你在做一些不寻常的事情,否则你应该避免在 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();

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. drop拥有数组的所有权,所以这是完全安全的。 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.正如另一个答案中提到的,几乎没有必要这样做,当盒子超出范围时,它会自动释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM