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);
}
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!().