dotcfg 0.3.0 is outCustom directories and project config discovery are now available.See what’s new →
dotcfg
Star on GitHub
Recipes

Examples

These are intentionally small snippets: copy the pattern you need, then shape the config type around your application. As real-world dotcfg integrations appear, this page can grow a separate showcase without turning the core docs into a gallery.

Optional configuration

Run normally when no config file exists.

Rust
let config: Option<AppConfig> = cfg.load()?;

Required configuration

Fail when the application has not been configured yet.

Rust
let config: AppConfig = cfg.load_or_error()?;

Create a default config

Create the file from your struct's Default implementation.

Rust
let config: AppConfig = cfg.load_or_default()?;

Change one typed value

Update one field without rebuilding the whole config struct.

Rust
cfg.set_val("server.port", 8080u16)?;
let port: u16 = cfg.get_as("server.port")?;

Use a custom directory

Useful for tests, portable setups, and project-local config.

Rust
let cfg = DotCfg::new("mytool")
    .at_dir("./.config");

Discover project configuration

Run a developer tool from a nested directory and find the nearest project config.

Rust
let cfg = DotCfg::new("mytool")
    .find_in_ancestors()?;

Environment-first reads

Let deployment or shell values override the saved file.

Rust
let cfg = DotCfg::new("mytool")
    .with_env_prefix("myapp");
let port: u16 = cfg.get_as("port")?;

CLI flags over saved config

The repository includes a complete Clap example using a common precedence pattern: CLI argument → config file → default value.

Pattern
let saved: AppConfig = cfg.load()?.unwrap_or_default();

let active = AppConfig {
    host: args.host.unwrap_or(saved.host),
    port: args.port.unwrap_or(saved.port),
    log_level: args.log_level.unwrap_or(saved.log_level),
};

Browse the repository examples ↗