envconfig-rs icon indicating copy to clipboard operation
envconfig-rs copied to clipboard

feat: add prefix support to nested fields

Open rliang opened this issue 8 months ago • 0 comments

Hi there, first of all thanks for this crate.

I'm opening a PR for supporting prefixing in nested structures. So it differs by #43 since that one supports prefixes on the structs themselves.

It solves a pain point in one of my codebases that we can't reuse structures:

#[derive(Envconfig)]
pub struct DbConfig {
    #[envconfig(from = "HOST")]
    pub host: String,
    #[envconfig(from = "PORT", default = "5432")]
    pub port: u16,
}

#[derive(Envconfig)]
pub struct Config {
    #[envconfig(nested)]
    pub foo: DbConfig,
    #[envconfig(nested)]
    pub bar: DbConfig,
}

In this example, I'd have to create another identical DbConfig struct for each database. But with this PR, we can reuse it:

#[derive(Envconfig)]
pub struct DbConfig {
    #[envconfig(from = "HOST")]
    pub host: String,
    #[envconfig(from = "PORT", default = "5432")]
    pub port: u16,
}

#[derive(Envconfig)]
pub struct Config {
    #[envconfig(nested, prefix = "FOO_")]
    pub foo: DbConfig,
    #[envconfig(nested, prefix = "BAR_")]
    pub bar: DbConfig,
}

rliang avatar May 12 '25 13:05 rliang