如何在Rust中执行有效的矢量初始化? [英] How to perform efficient vector initialization in Rust?

查看:84
本文介绍了如何在Rust中执行有效的矢量初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rust中填充结构向量的好方法是:

What's a good way to fill in a vector of structs in Rust where:


  • 大小是动态的,但在当时是已知的

  • 不会首先将内存初始化为虚拟值。

  • 不会在内存已满时重新分配内存。
  • li>
  • 在此示例中,向量的所有成员总是 初始化。
    (与Rusts保证没有未定义的行为一样)。

  • The size is dynamic, but known at the time of initialization.
  • Doesn't first initialize the memory to a dummy value.
  • Doesn't re-allocate memory as its filled.
  • In this example, all members of the vector are always initialized.
    (In keeping with Rusts assurance of no undefined behavior).

理想地


  • Doesn' t索引检查每个索引访问
    (因为在声明向量时应该知道大小,这是可能的。)。

  • 不需要不安全
    (不确定这是否合理,但是编译器_could_会检测到所有值始终都被填充,从而在不安全的块中允许这种逻辑)。

  • Doesn't index check each index access
    (since the size is known when declaring the vector this should be possible).
  • Doesn't require unsafe
    (Not sure if this is reasonable, however the compiler _could_ detect that all values are always filled, allowing such logic in an unsafe block).

C等效项是:

struct MyStruct *create_mystruct(const uint n) {
    struct MyStruct *vector = malloc(sizeof(*vector) * n);
    for (uint i = 0; i < n; i++) {
        /* any kind of initialization */
        initialize_mystruct(&vector[i], i);
    }
    return vector;
}

我正在移植一些C代码,该代码在一个简单的循环中填充了一个数组,所以我想知道是否有 Rustic 方法以零或至少最小的开销执行这样的常见任务?

I'm porting over some C code which fills an array in a simple loop, so I was wondering if there was a Rustic way to perform such a common task with zero or at least minimal overhead?

通常,此代码的Rust版本需要一些额外的检查,最接近的等效项是什么?

If there are typically some extra checks needed for the Rust version of this code, what's the nearest equivalent?

推荐答案

只需使用地图收集

struct MyStruct(usize);

fn create_mystructs(n: usize) -> Vec<MyStruct> {
    (0..n).map(MyStruct).collect()
}

在安全的Rust中初始化没有意义,因为您需要具有访问未初始化值的能力,这是不安全的。 Iterator :: size_hint 方法可以在收集到容器中时使用,以确保进行最少数量的分配。

"Initializing" doesn't make sense in safe Rust because you'd need to have the ability to access the uninitialized values, which is unsafe. The Iterator::size_hint method can be used when collecting into a container to ensure that a minimum number of allocations is made.

基本上,我相信优化器将在此处执行正确的操作。如果没有,我相信它最终会成功。

Basically, I'd trust that the optimizer will do the right thing here. If it doesn't, I'd believe that it eventually will.

这篇关于如何在Rust中执行有效的矢量初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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