更有效地初始化数组保持结构 [英] Initialize array holding struct more efficiently

查看:109
本文介绍了更有效地初始化数组保持结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

const N: usize = 10000;
const S: usize = 7000;

#[derive(Copy, Clone, Debug)]
struct T {
    a: f64,
    b: f64,
    f: f64
}

fn main() {
    let mut t: [T; N] = [T {a: 0.0, b: 0.0, f: 0.0}; N];

    for i in 0..N {
        t[i].a = 0.0;
        t[i].b = 1.0;
        t[i].f = i as f64 * 0.25;
    }

    for _ in 0..S {
        for i in 0..N {
            t[i].a += t[i].b * t[i].f;
            t[i].b -= t[i].a * t[i].f;
        }
        println!("{}", t[1].a);
    }
}

我不确定为什么必须以这种方式初始化数组t.第一个for循环旨在将包含包含结构的数组初始化为其各自的值.

I'm unsure why the array t must be initialized that way. The first for-loop is intended to initialize the array with the containing struct to their respective values.

当我尝试直接使用数组省略初始化时:

When I try to omit the initialization directly with the array:

let mut t: [T; N];

我收到以下错误:

错误[E0381]:使用可能未初始化的变量:t

error[E0381]: use of possibly uninitialized variable: t

所有的for循环都是这样,我只想知道数组是否有更聪明的方法,并且它是使用第一个for循环进行初始化的.

All for-loops are intended to be as such, I just want to know if there is a smarter way for the array and it's initialization with the first for-loop.

推荐答案

我不确定为什么必须以这种方式初始化数组t.

因为Rust不允许您(全部或部分)触摸未初始化的值.编译器不够聪明,无法证明循环会确定地初始化所有内容,因此它只是禁止这样做.

Because Rust doesn't let you touch (entirely or partially) uninitialised values. The compiler isn't smart enough to prove that the loop will definitely initialise everything, so it just forbids it.

现在, optimiser 是另外一回事了.可以 注意到初始化是多余的,从理论上讲可以跳过它.该代码和当前的编译器似乎没有这样做.这就是优化.

Now, the optimiser is a different story. That can notice that the initialisation is redundant and skip it... in theory. It doesn't appear to do so with that code and the current compiler. Such is optimisation.

我只想知道数组是否有更聪明的方法,并且它是使用第一个for循环进行初始化的.

I just want to know if there is a smarter way for the array and it's initialization with the first for-loop.

聪明的方法是将代码保持原样.从统计上讲,这不太可能成为瓶颈.如果分析表明它瓶颈,那么您可以使用

The smart way is to just leave the code as-it-is. Statistically speaking, it's unlikely to be a bottleneck. If profiling suggests that it is a bottleneck, then you can use uninitialised. However, note that doing so can lead to undefined behaviour if you use it wrong. Although not an exhaustive list, you definitely avoid using it on any type that is not Copy.

如果确实需要使用 ,我强烈建议您还调整第一个循环,以使忘记初始化元素结构中的字段成为不可能:

If you do need to use it, I strongly recommend also adjusting the first loop to make forgetting to initialise an element or a field in the structure impossible:

    let mut t: [T; N] = unsafe { ::std::mem::uninitialized() };

    for (i, e) in t.iter_mut().enumerate() {
        *e = T {
            a: 0.0,
            b: 1.0,
            f: i as f64 * 0.25,
        }
    }

这篇关于更有效地初始化数组保持结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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