我如何从函数结果的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
}
如果我按照mccarton的建议使用
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
}
关于rust - 从功能获得的mod中获取结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62981701/