【问题标题】:Load config from file and use it in rust code everywhere从文件加载配置并在任何地方的 rust 代码中使用它
【发布时间】:2021-02-07 16:23:27
【问题描述】:

我是 rust 新手,想了解如何从文件加载配置以在代码中使用它。

在 main.rs 和其他文件中,我想使用从文件加载的配置:

mod config;
use crate::config::config;

fn main() {
  println!("{:?}", config);
}

在 config.rs 文件中,我想在运行时读取 backend.conf 文件一次,检查它并将其存储为不可变的以在任何地方使用它。到目前为止,我的尝试只得到了错误:

use hocon::HoconLoader;
use serde::Deserialize;

#[derive(Deserialize, Debug)]
pub struct Config {
    pub host: String,
    pub port: String,
}

pub const config: Config = get_config(); //err: calls in constants are limited to constant functions, tuple structs and tuple variants

fn get_config() -> Config {
    let config: Config = HoconLoader::new() // err: could not evaluate constant pattern
        .load_file("./backend.conf")
        .expect("Config load err")
        .resolve()
        .expect("Config deserialize err");

    config
}

我无法理解的是,你应该如何在 rust 中做到这一点?


正如 Netwave 建议的那样,它是这样工作的:

main.rs:

 #[macro_use]
   extern crate lazy_static;

    mod config;
    use crate::config::CONFIG;

    fn main() {
      println!("{:?}", CONFIG.host);
    }

config.rs:

use hocon::HoconLoader;
use serde::Deserialize;

#[derive(Deserialize, Debug)]
pub struct Config {
    pub host: String,
    pub port: String,
}

lazy_static! {
    pub static ref CONFIG: Config = get_config();
}

fn get_config() -> Config {
    let configs: Config = HoconLoader::new()
        .load_file("./backend.conf")
        .expect("Config load err")
        .resolve()
        .expect("Config deserialize err");

    configs
}

后端配置:

{
    host: "127.0.0.1"
    port: "3001"
}

【问题讨论】:

标签: rust


【解决方案1】:

使用lazy_static:

lazy_static!{
    pub static ref CONFIG: Config = get_config(); 
}

或者,您可以在程序入口点加载它并将其附加到某种上下文中,然后将其传递到您需要的地方。

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多