config_tools

Derive Macro FromSection

source
#[derive(FromSection)]
Expand description

Derives the Section trait for a struct.

This macro generates an implementation of the Section trait for a struct, enabling automatic parsing of its fields from a BTreeMap<String, String>, which represents a section from a configuration file.

Each field in the struct must implement FromStr, as the macro will attempt to parse the corresponding string value for each field in the section map. There is no need to import the Section trait, as the macro will do so automatically.

ยงExample

#[derive(FromSection)]
struct ServerConfig {
    host: String,
    port: u16,
}

let config = Config::load("config.ini")?;
let server_section = config.section("Server").unwrap();
let server_config = ServerConfig::from_section(server_section)?;
println!("{:?}", server_config);

In this example, the ServerConfig struct will automatically be populated from the [Server] section of the config.ini file, with values for host and port.