Store configs in HashMap of enum vs variables

Hello.

My script need some configurations like thresholds, paths, HashMap.. etc.

And there are many functions and many of them need the config values.
Some functions need 10 more config values.

In this situtation, How would I store the config variables?

I came up with two ways (probably bad. I'm noob here)

  1. to HashMap having an enum which have multiple types(HashMap, String, i64.. etc)
  2. all configs to their respective variables. (let thresh1 = 10; let info_map = HashMap... etc.)

Or A new way better than the above.

Any help would be appreciated. Thanks.

I usually use a struct for config values.

use std::path::PathBuf;

struct Config {
    threshold_1: i32,
    threshold_2: f64,
    file_path: PathBuf,
    // More fields
}

Then you can do nice stuff like implementing the Default trait so you don't have to fill in all fields.

Also there are crates to fill such a struct automatically from env variables or a config file if there are sensible defaults.

Your script then looks something like this

let config = Config {
    threshold_1: 10,
    threshold_2: 3.14,
    file_path: PathBuf::from("./data/file1.csv"),
    ..Default::default()
}

let mut data = load_data(&config);
do_statistics(&mut data, &config);
save_to_cloud(&data, &config);
3 Likes

Yeah, you usually don't want to model your data with loosely-typed trees of arbitrary values. Chances are configuration data is very strongly typed. There's not many kinds of data you can provide if e.g. you need an API key or a file path. Those have to be ApiKeys and Paths.

The easiest way to automate all of this is to pick a serialization format (e.g., JSON, YAML, or TOML), #[derive(Serialize, Deserialize)] on your config struct, and load/dump it using Serde.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.