Initialize array holding struct more efficiently

Viewed 1135

I have the following code:

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

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];

I get the following error:

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

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.

2 Answers
Related