Accessing global static values from modules

Following the rust book, I have migrated all the logic of my app into lib.rs, with the main.rs calling the lib.rs run, parsing a command line struct, like so.

main.rs

use std::process;
#[macro_use]
extern crate log;
use structopt::StructOpt;

#[derive(StructOpt, Debug)]
pub struct CliOpt {
    #[structopt(short = "c", long = "config-file", parse(from_os_str))]
    config_file_path: std::path::PathBuf,
}

lazy_static! {
    pub static ref CFG: CliOpt = CliOpt::from_args();
}

fn main() {
    if let Err(err) = mylib::run() {
        error!("{}", err);
        process::exit(1);
    }
}

How do I make this global static variable CFG declared in main.rs to be accessible in other parts of the program (like lib.rs) ?

I've tried a few things: Using crate::CFG only works if I place the lazy_static! block inside the lib.rs file. That creates a different set of problems (like how to define and run tests).

Alternately, I could pass CFG as a parameter to mylib::run() -- which also works, but I'd prefer to have CFG as a global to simplify access and simplify function signatures.

Any help would be appreciated. Any other design to share global configuration values would also be appreciated!

The lib.rs file cannot access stuff in main.rs. You should think of main.rs as a separate crate from lib.rs, that has a dependency on lib.rs, and you can't have dependency cycles in Rust.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.