从文件加载配置并在所有 Rust 代码中使用它

RTW*_*RTW 8 rust

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

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

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

fn main() {
  println!("{:?}", config);
}
Run Code Online (Sandbox Code Playgroud)

在 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
}
Run Code Online (Sandbox Code Playgroud)

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


正如 Netwave 所建议的,它的工作原理如下:

主要.rs:

 #[macro_use]
   extern crate lazy_static;

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

    fn main() {
      println!("{:?}", CONFIG.host);
    }
Run Code Online (Sandbox Code Playgroud)

配置.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
}
Run Code Online (Sandbox Code Playgroud)

后端.config:

{
    host: "127.0.0.1"
    port: "3001"
}
Run Code Online (Sandbox Code Playgroud)

Net*_*ave 6

使用lazy_static

lazy_static!{
    pub static ref CONFIG: Config = get_config(); 
}
Run Code Online (Sandbox Code Playgroud)

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