FromConfig

Derive Macro FromConfig 

Source
#[derive(FromConfig)]
{
    // Attributes available to this derive:
    #[config]
}
Expand description

Automatic derive FromConfig instance.

We use annotation attributes to customize the derived instances’ behavior. All attributes in cfg-rs have format #[config(key = value, key2 = value2)].

§Struct Annotation Attribute

  • #[config(prefix = "cfg.app")]

This attr will lead to implement trait FromConfigWithPrefix.

#[derive(FromConfig)]
#[config(prefix = "cfg.test")]
struct Test {
  //fields...   
}

§Crate Annotation Attribute

  • #[config(crate = "cfg")]

This attr will specify the crate name of cfg-rs in generated code. It is useful when you rename the crate in Cargo.toml.

// In Cargo.toml
// [dependencies]
// cfg = { path = "../cfg-rs" }

#[derive(FromConfig)]
#[config(crate = "cfg")]
struct Test {
  //fields...   
}

§Field Annotation Attribute

  • #[config(name = "val")]

This attr will replace the default config partial key, which is name of field.

#[derive(FromConfig)]
struct Test {
  val: u8,
  #[config(name = "val")]
  other: u8, // This field `other` will use the same partial key as `val`.
}
  • #[config(default = true)]

This attr provides default value for underlying field.

#[derive(FromConfig)]
struct Test {
  enabled: bool, // User must provide value for this field.
  #[config(default = true)]
  enabled_with_default: bool, // This field has default value `true`.
}