6

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"
}
ZiiMakc
  • 31,187
  • 24
  • 65
  • 105
  • 2
    You could use the [`lazy_static` crate](https://crates.io/crates/lazy_static). However, that might make error handling a bit more troublesome. Instead I'd load the config in main, and pass a reference to the things that need it. – vallentin Feb 07 '21 at 16:28
  • Does this answer your question? [Is it possible to use global variables in Rust?](https://stackoverflow.com/questions/19605132/is-it-possible-to-use-global-variables-in-rust) – pretzelhammer Feb 07 '21 at 16:28

1 Answers1

5

Use 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.

Netwave
  • 40,134
  • 6
  • 50
  • 93