Possible to calculate array values during compilation?

I have an array of lets say 5000 values which involve a somewhat complex calculation (f64).
Would it be possible to calculate this many values into an array upon compilation?
The calculation does not depend on user input and is essentially entirely hardcoded.
I would run a for loop and save them to a vec normally, but can this be optimized?

This is probably overkill in my case, but I just wanted to know on how complex tasks rust compiler ca optimize.

if and loops inside constant functions were stabilized last week; this is possible on the nightly compiler now and should make it to stable before long. For example:

const FIB: [usize; 20] = {
    let mut result = [1usize; 20];
    let mut x = 2;
    while x < result.len() {
        result[x] = result[x - 1] + result[x - 2];
        x = x + 1;
    }
    result
};

fn main() {
    println!("{:?}", FIB);
}

(Playground)

2 Likes

@2e71828
Nice! But does it work for larger numbers as well? I heard somewhere that arrays have a very low limited size

Seems fine, as long as you don’t rely on auto-implemented traits: (Playground)

(I had to change away from Fibonacci b/c it was overflowing a u128)

For large and complex data that is truly constant I use include_bytes!(). This requires generating the data beforehand, e.g. using another executable which you run before committing or publishing the code.

For things that really need to be run at compilation time by each user, there's also build.rs. You can generate either binary files (for include_bytes!()) or a Rust source code for include!().

4 Likes

include_bytes!() is very interesting! Perfect for such tasks