#failed to initialize variables from `.env`

23 messages · Page 1 of 1 (latest)

wide geyser
#
use std::sync::LazyLock;

pub static DATABASE_URL: LazyLock<String> = LazyLock::new(|| {
    dotenv::dotenv().ok();
    std::env::var("DATABASE_URI").unwrap()
});
pub static SECRET_KEY: LazyLock<String> = LazyLock::new(|| {
    dotenv::dotenv().ok();
    std::env::var("SUPER_SECRET_KEY").unwrap()
});

I wrote this code in my lib.rs file. While I am trying to debug this variable its showing uninit
Also how to do this with only one dotenv::dotenv().ok()

fervent sapphire
#

Make a struct with both your field, and then make a lazy lock with it, and then call dotenv one once and make the struct read both env vars. That takes care of the one call.

wide geyser
#

hey can you show it please?

fervent sapphire
#

a bit later

wide geyser
# fervent sapphire a bit later
struct Foo {
  db: String,
  secret: String,
}
impl Foo {
  fn new() -> Self {
    dotenv::dotenv().ok();
    Self {
      db: std::env::var("DATABASE_URI").unwrap()
      secret: std::env::var("SUPER_SECRET_KEY").unwrap()
    }
  }
}
pub static FOO: LazyLock<Foo> = LazyLock::new(Foo::new);

is this correct?

fervent sapphire
#

the new function is correct, the field types arent, just make them String and then wrap the entire struct in lazylock

#

now it is yeah

wide geyser
fervent sapphire
#

what is it showing

wide geyser
#

while I am trying to debug

[src/main.rs:3:5] &restfullapi::CONFIG = LazyLock(
    <uninit>,
)
#
#[allow(non_snake_case)]
#[derive(Debug)]
pub struct AppConfig {
    DATABASE_URI: String,
    SECRET_KEY: String,
}

impl AppConfig {
    pub fn new() -> Self {
        dotenv::dotenv().ok();
        Self {
            DATABASE_URI: std::env::var("DATABASE_URI").unwrap(),
            SECRET_KEY: std::env::var("SUPER_SECRET_KEY").unwrap(),
        }
    }
}

pub static CONFIG: LazyLock<AppConfig> = LazyLock::new(AppConfig::new);
wide geyser
dreamy totem
fervent sapphire
#

do instead of &CONFIG do &*CONFIG

dreamy totem
#

you literally copy pasted the same question in another thread

dreamy totem
fervent sapphire
#

BRUHHH

wide geyser
dreamy totem
wide geyser
#

you wasted my time.

dreamy totem
#

lmao

wide geyser
#

please dont do that again

dreamy totem
#

I literally told you what was wrong and why and how to fix it