我刚接触 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/