从函数的结果mod中获取结构



如何共享函数结果mod中的结构,以便每次需要环境变量时都不会重新运行env::get((函数。

src/main:

mod env;
async fn main() {
println!("{}", env::get().profile);
println!("{}", env::get().redis);
}

src/env:

use serde::Deserialize;
extern crate dotenv;
#[derive(Deserialize, Debug)]
pub struct Config {
pub redis: String,
pub profile: String,
}
pub fn get() -> Config {
dotenv::dotenv().expect("Failed to read .env file");
let env = match envy::from_env::<Config>() {
Ok(config) => config,
Err(e) => panic!("{:#?}", e),
};
env
}

如果我像mcarton建议的那样使用lazy_static,我如何在main中获得ENV?

src/env:

use serde::Deserialize;
extern crate dotenv;

#[derive(Deserialize, Debug)]
pub struct Config {
pub redis: String,
pub profile: String,
}
pub fn get() -> Config {
dotenv::dotenv().expect("Failed to read .env file");
let env = match envy::from_env::<Config>() {
Ok(config) => config,
Err(e) => panic!("{:#?}", e),
};
env
}
lazy_static! {
static ref ENV: Config = {
dotenv::dotenv().expect("Failed to read .env file");
let env = match envy::from_env::<Config>() {
Ok(config) => config,
Err(e) => panic!("{:#?}", e),
};
env
};
}

这里是:

use serde::Deserialize;
extern crate dotenv;
#[derive(Deserialize, Debug)]
pub struct EnvConfig {
pub redis: String,
pub profile: String,
}
lazy_static! {
pub static ref ENV: EnvConfig = {
dotenv::dotenv().expect("Failed to read .env file");
let env = match envy::from_env::<EnvConfig>() {
Ok(config) => config,
Err(e) => panic!("{:#?}", e),
};
env
};
}
pub fn get() -> &'static ENV {
&ENV
}

最新更新