Known at startup instead of at compile-time?

Does rust have a way to make a compile-time value configurable? Instead of "known at compile-time", it would be "known at startup", but provide the same performance as known at compile-time. Does this exist?

To add some context, I have a project involving a table data structure, and I'd appreciate the benefit of knowing the table dimensions at compile-time, but I won't because I'm writing a library to be consumed and reused where table dimensions will vary between use cases. Because my library needs to compile into a NIF for elixir, it needs to be compiled, but the elixir programs that users will write will likely know the table dimensions at compile-time, but this needs to be passed into rust-land at startup. I would think this would be possible.

You could go for environment variables, but it wont be as efficient as hard-coded table dimensions.

GitHub - mmastrac/rust-ctor: Module initialization/global constructor functions for Rust seems interesting for your requirement. It's not clear to me exactly what the "runtime" version of the resulting #[ctor]'ed static is when using this crate. I know the crate inventory uses #[ctor] too.

Have you started by just using once_cell or lazy_static and initializing this table on-demand, once only, after startup? The overhead of that is relatively low and this solution is the usual one, if it works for you.

1 Like

I mean, when you know at compile time that the table has a length of four, the compiler can just emit whatever assembly instructions you need in your loop four times in a row. You're never going to get optimizations like this if you don't know the dimension at compile-time.

I suppose there is one exception, namely that you could compile parts of your program at runtime with something like JIT compilation.


I'm assuming this is beyond the scope of just:

pub struct Table<T, const R: usize, const C: usize> {
    data: [[T; R]; C], // or vice-versa

But I'd like to learn more about where the hangups with this come in the FFI realm.

Also, have you seen Nx (Numerical Elixir)?

If you want a piece of data that is initialized once and then read, you can use once_cell::Lazy.

1 Like