[英]How to perform efficient vector initialization in Rust?
What's a good way to fill in a vector of structs in Rust where: 在Rust中填充结构向量的好方法是:
And ideally 理想地
unsafe
unsafe
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
. 只需使用
map
并collect
。
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.