greyblake/envconfig-rs

Possible to use Enums?

naftulikay opened this issue · 5 comments

I'm pretty used to using something like serde for serializing enums as strings:

#[derive(Serialize, Deserialize)]
pub struct Data {
    pub logging_format: LoggingFormat,
}

#[derive(Serialize, Deserialize)]
pub enum LoggingFormat {
    #[serde(rename = "json")]
    Json,
    #[serde(rename = "plain")]
    Plain,
}

Is it possible to do something similar with Envconfig?

Unfortunately not at the moment.
As alternative I may suggest you to use Envy, it is based on Serde, and as result supports all Serde features.

Thank you!

You're welcome!
I will reopen the issue as a reminder for myself to investigate ability of adding enums when I have some free time :)

If you derive strum_macros EnumString, you get the FromStr implementation automatically, and you can also derive the values to be lower cased. This is what I have done to work around the issue, and its as simple as adding the derive attr.

use envconfig::Envconfig;
use std::str::FromStr;
use strum_macros::EnumString;

#[derive(Debug, Envconfig)]
struct Config {
    #[envconfig(from = "BAR", default = "Foo")]
    bar: Bar,
    #[envconfig(from = "FOO_BAR")]
    foobar: String,
}

#[derive(Debug, EnumString)]
enum Bar {
    Foo,
    Quxx,
}

fn main() {
    let config = Config::init_from_env().unwrap();
    println!("Config is {:?}", config);
    match config.bar {
        Bar::Foo => println!("We are foo"),
        Bar::Quxx => println!("We are Quxx"),
    }
}

Command to run:

FOO_BAR="testing" BAR="Quxx" cargo run

Output is:

Config is Config { bar: Quxx, foobar: "testing" }
We are Quxx

Thanks everyone. I've added an example with strum and enum to the README.
Closing the issue...