【发布时间】: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"
}
【问题讨论】:
-
您可以使用
lazy_staticcrate。但是,这可能会使错误处理更加麻烦。相反,我会在 main 中加载配置,并传递对需要它的东西的引用。
标签: rust