1

I want to set a top level const in a Rust file to the value of an environment variable. In something like nodejs which I'm more used to, I would do something like:

const my_const = process.env['ENV_VAR_NAME'] ? process.env['ENV_VAR_NAME'] : 'FALLBACK_VALUE'

How do I achieve such a thing with Rust?

I have tried many things, such as

pub const my_const: &str = option_env!("ENV_VAR_NAME").unwrap_or("FALLBACK_VALUE");

But this yields the error calls in constants are limited to constant functions, tuple structs and tuple variants

I have also tried

pub const my_const: &str = if !option_env!("ENV_VAR_NAME").is_none() { env!("ENV_VAR_NAME") } else { "FALLBACK_VALUE" };

However, this doesn't work because env! is a compile-time macro and generates a compile time error if the environment variable doesn't exist.

WhoopsBing
  • 493
  • 1
  • 6
  • 12
  • The problem here is that you want a const from something which can't be a const (as of current rust `std::env::var` isn't a const fn). A solution could be to use lazy_static. But using const or static in Rust for something which fundamentally is dynamically built is usually a design problem. – Denys Séguret Apr 20 '21 at 18:30
  • 1
    Would you like to read the value of the environment variable at compile time or at runtime? A `const` in Rust is a compile time constant, so that would only work if that is what you want. If you want a runtime constant, your question is answered in [Populating a static/const with an environment variable at runtime in Rust](https://stackoverflow.com/questions/37405835/populating-a-static-const-with-an-environment-variable-at-runtime-in-rust). – Sven Marnach Apr 20 '21 at 18:34
  • Related: [Is it possible to initialize a variable from an environment variable at compilation time?](https://stackoverflow.com/questions/51620782/is-it-possible-to-initialize-a-variable-from-an-environment-variable-at-compilat) – Sven Marnach Apr 20 '21 at 18:36

0 Answers0