How to Read Configuration Files in Rust (config crate)

Read configuration files in Rust by adding the config crate and using Config::builder to merge sources like TOML files into a single object.

Add the config crate to your Cargo.toml, then use Config::builder() to merge sources like files and environment variables before building the final configuration object.

[dependencies]
config = "0.14"
use config::{Config, File, FileFormat};

fn main() -> Result<(), config::ConfigError> {
    let settings = Config::builder()
        .add_source(File::with_name("config.toml").format(FileFormat::Toml))
        .build()?;

    let port: u16 = settings.get("server.port")?;
    println!("Port: {}", port);
    Ok(())
}