简体   繁体   English

如何在Rust中执行有效的矢量初始化?

[英]How to perform efficient vector initialization in Rust?

What's a good way to fill in a vector of structs in Rust where: 在Rust中填充结构向量的好方法是:

  • 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). (与Rusts保证没有未定义的行为一致)。

And ideally 理想地

  • Doesn't index check each index access 不索引检查每个索引访问
    (since the size is known when declaring the vector this should be possible). (由于在声明向量时已知大小,因此应该可以)。
  • Doesn't require unsafe 不需要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). (不确定这是否合理,但是编译器_could_会检测到所有值始终都被填充,从而在不安全的块中允许这种逻辑)。

The C equivalent is: 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;
}

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? 我正在移植一些在一个简单循环中填充数组的C代码,所以我想知道是否有一种Rustic方式可以以零或至少最小的开销执行这样的常见任务?

If there are typically some extra checks needed for the Rust version of this code, what's the nearest equivalent? 如果此代码的Rust版本通常需要进行一些额外的检查,那么最接近的等效项是什么?

Just use map and collect . 只需使用mapcollect

struct MyStruct(usize);

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

"Initializing" doesn't make sense in safe Rust because you'd need to have the ability to access the uninitialized values, which is unsafe. 在安全的Rust中,“初始化”没有意义,因为您需要具有访问未初始化值的能力,这是不安全的。 The Iterator::size_hint method can be used when collecting into a container to ensure that a minimum number of allocations is made. 在收集到容器中时,可以使用Iterator::size_hint方法来确保分配的数量最少。

Basically, I'd trust that the optimizer will do the right thing here. 基本上,我相信优化器会在这里做正确的事情。 If it doesn't, I'd believe that it eventually will. 如果没有,我相信最终会的。

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

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