How to use table type

Hi all,
I'm very new to the Rust programming language but have quite extensive C knowledge. The latter may be problematic for me though.

Anyway, I need to use a configuration file in my current project and have found the config crate that can parse several types of config files and it seems to suit my need.

The toml config file that I've created looks somewhat similar to this example:

[stuff]

[stuff.data1]
key = "value1"

[stuff.data2]
key = "value2".

Using the Config crate, I can get a table from this config file but I need to figure out how many data* entries there are in the table and this is where I get stuck.

Since I'm used to C, I'm really not used to more complex data types than nested structs, which probably makes the documentation somewhat unclear to me.

Could someone point me in the right direction or even better to a sample of rust code that does what I need?

By "table", you presumably mean a HashMap data structure.

The config crate can indeed parse TOML files into a HashMap. You can then examine the number of keys in the map. Something like the following should work:

use config::{Config, File, FileFormat, Map};

#[derive(serde::Deserialize, Clone, Debug)]
pub struct Settings {
    pub stuff: Map<String, Map<String, String>>,
}

fn main() {
    let f = File::new("<name of toml file here>.toml",
                      FileFormat::Toml);
    let settings = Config::builder()
        .add_source(f.required(true))
        .build()
        .unwrap();

    let settings: Settings = settings.try_deserialize().unwrap();
    let num_data = settings.stuff.keys().len();

    println!("There are {num_data} stuff.data sections");
}

Thank you very much for your reply!

This pointed me in the right direction and now I'm able to use more complex config files as well :slight_smile:

Really appreciated!

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.