如何在Rust的运行时分配数组? [英] How do I allocate an array at runtime in Rust?

查看:276
本文介绍了如何在Rust的运行时分配数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一旦分配了阵列,如何手动释放它?在不安全模式下可以进行指针算术运算吗?

Once I have allocated the array, how do I manually free it? Is pointer arithmetic possible in unsafe mode?

类似于C ++:

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

Rust中有等效的代码吗?

Is there any equivalent code in Rust?

推荐答案

根据您的问题,我建议阅读 Rust预订(如果尚未预订).成语的Rust几乎从不涉及手动释放内存.

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.

对于等效于动态数组的内容,您需要 Vector .除非您做一些不寻常的事情,否则应避免在Rust中使用指针算术.您可以将以上代码编写为:

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

这篇关于如何在Rust的运行时分配数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆