简体   繁体   English

从文件加载配置并在 rust 代码中到处使用它

[英]Load config from file and use it in rust code everywhere

I'm new to rust and want to understand how to load config from file to use it in code.我是 rust 的新手,想了解如何从文件加载配置以在代码中使用它。

In main.rs and other files i want to use config loaded from file:在 main.rs 和其他文件中,我想使用从文件加载的配置:

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

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

In config.rs file i want to read backend.conf file once at runtime, check it and store it as immutable to use it everywhere.在 config.rs 文件中,我想在运行时读取 backend.conf 文件一次,检查它并将其存储为不可变的以在任何地方使用它。 My attempts so far got me only errors:到目前为止,我的尝试只得到了错误:

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
}

What i can't wrap my head around, is to how you should do it in rust?我无法理解的是,你应该如何在 rust 中做到这一点?


As Netwave suggested this is how it works:正如 Netwave 建议的那样,它是这样工作的:

main.rs: main.rs:

 #[macro_use]
   extern crate lazy_static;

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

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

config.rs:配置.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"
}

Use lazy_static :使用lazy_static

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

Alternatively, you may load it in the program entry point and attach it in some kind of context and pass it around where you need it.或者,您可以将其加载到程序入口点并将其附加到某种上下文中,然后将其传递到您需要的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM