Unit-only enums
Configurations typically use enums to support multiple values within a specific
setting. To simplify this process, and to provide streamlined interoperability
with Config, we offer a
ConfigEnum trait and macro
that can be derived for enums with unit-only variants.
#![allow(unused)]
fn main() {
#[derive(ConfigEnum)]
enum LogLevel {
Info,
Error,
Debug,
Off
}
}
When paired with Config, it’ll look like:
#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
pub log_level: LogLevel
}
}
This enum will generate the following implementations:
- Provides a static
T::variants()method, that returns a list of all variants. Perfect for iteration. - Implements
FromStrandTryFromfor parsing from a string. - Implements
Displayfor formatting into a string.
Attribute fields
The following fields are supported for the #[config] container attribute:
before_parse- Transform the incoming string before parsing, so that loosely cased input still matches. Accepts the same case names asrename_all:lowercase,UPPERCASE,PascalCase,camelCase,snake_case,SCREAMING_SNAKE_CASE,kebab-case, andSCREAMING-KEBAB-CASE.
#![allow(unused)]
fn main() {
#[derive(ConfigEnum)]
#[config(before_parse = "kebab-case")]
enum ExampleEnum {
// ...
}
}
With the above, very_high, VeryHigh, and VERY HIGH all parse into the same variant.
And the following for serde compatibility:
renamerename_all- Has no default. Variant names are used exactly as written unless this is set.
Variants
The following fields are supported for the #[variant] variant attribute:
fallback- Marks the variant as the fallback.
And the following for serde compatibility:
aliasrename- Overrides (explicitly sets) the string value used for parsing and formatting.
Deriving common traits
All enums (not just unit-only enums) typically support the same derived traits, like Clone, Eq,
etc. To reduce boilerplate, we offer a
derive_enum! macro that will
apply these traits for you.
#![allow(unused)]
fn main() {
derive_enum!(
#[derive(ConfigEnum)]
enum LogLevel {
Info,
Error,
Debug,
Off
}
);
}
This macro will inject the following attributes:
#![allow(unused)]
fn main() {
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "kebab-case")]
}