rust - 从作为函数结果的 mod 中获取结构
问题描述
我如何从作为函数结果的 mod 共享结构,以便每次我需要环境变量时我都不会重新运行 env::get() 函数。
源/主要:
mod env;
async fn main() {
println!("{}", env::get().profile);
println!("{}", env::get().redis);
}
源/环境:
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
按照 mcarton 的建议使用,我怎样才能在 main 中获得 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
}
推荐阅读
- javascript - Next.js SSR/ISR 为非静态页面创建 HTML 静态文件
- c# - 为什么这个字符串不知从哪里出现
- amazon-web-services - 无法将 Amazon SQS 附加到 Amazon S3 事件通知
- python - 如何从点分隔字符串中的单词中挑选出第一个字母
- python - 如何将索引、列表值插入字典值(基于另一个列表的长度)?
- java - 删除对象时是否使用诸如 isDestroyed 之类的布尔值最佳实践?
- html - #id:hover { background: no-repeat url(...);} 不起作用?
- typescript - 如何将动态参数名称设置为类型定义
- amazon-web-services - 为什么我的 S3 存储桶策略拒绝跨账户访问?
- javascript - 通过 java 脚本更改货币 Shopify