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!