How to programatically define a static array in Rust?

Viewed 93

I'm trying to make a piece of my code more performant by using a static lookup table to avoid calls to a slow function, something like this:

fn my_slow_fn(x: usize) -> f64 {...}

const TABLE_SIZE: usize = 100;
static TABLE_VALUES: [f64; TABLE_SIZE] = (0..TABLE_SIZE)
  .map(my_slow_fn)
  .collect::<Vec<_>>()
  .try_into()
  .unwrap();

fn my_fast_fn(x: f64) -> f64 {
  let table_idx = get_table_idx(x)
  TABLE_VALUES[table_idx] // much faster than calling my_slow_fn(table_idx)
}

But the above code isn't legal because I can't make calls to non-constant functions when creating a static variable. How can I cleanly initialize this lookup table exactly once for the duration of the program?

My crate is a library, so I have no main function.

0 Answers
Related