首页 > 解决方案 > 从作为函数结果的 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
    };
}

标签: rust

解决方案


这里是:

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
}

推荐阅读