rust - 从文件加载配置并在所有地方的rust代码中使用它

标签 rust

我刚接触 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
}
backend.config:
{
    host: "127.0.0.1"
    port: "3001"
}

最佳答案

使用 lazy_static :

lazy_static!{
    pub static ref CONFIG: Config = get_config(); 
}
或者,您可以将其加载到程序入口点,并将其附加在某种上下文中,然后将其传递到需要的地方。

关于rust - 从文件加载配置并在所有地方的rust代码中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66090188/

相关文章:

rust - 你如何在 Rust 中使用父模块导入?

rust - 为什么将rand/rand_core与#![no_std]一起使用会导致 “duplicate lang item”?

rust - 如何借用一个字段进行序列化,但在反序列化时创建它?

rust - 循环内借用

rust - 如何将动态分配与以迭代器作为参数的方法一起使用?

rust - 为什么使用rust 使用rsi将参数传递给fn指针

使用rust 柴油机 : the trait bound `NaiveDateTime: Deserialize<' _>` is not satisfied

rust - 我如何(切片)在拥有的 Vec 上与非复制元素进行模式匹配?

collections - Rust 有集合特性吗?

rust - 错误 : cannot satisfy dependencies so `std` only shows up once