I'm new to rust and want to understand how to load config from file to use it in code.
In main.rs and other files i want to use config loaded from file:
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. 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?
As Netwave suggested this is how it works:
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"
}