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
FromStr
andTryFrom
for parsing from a string. - Implements
Display
for formatting into a string.
Attribute fields
The following fields are supported for the #[config]
container attribute:
before_parse
- Transform the variant string value before parsing. Supportslowercase
orUPPERCASE
.
#![allow(unused)] fn main() { #[derive(ConfigEnum)] #[config(before_parse = "UPPERCASE")] enum ExampleEnum { // ... } }
And the following for serde compatibility:
rename
rename_all
- Defaults tokebab-case
.
Variants
The following fields are supported for the #[variant]
variant attribute:
fallback
- Marks the variant as the fallback.value
- Overrides (explicitly sets) the string value used for parsing and formatting. This is similar to serde’srename
.
And the following for serde compatibility:
alias
rename
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")] }