#[derive(ConfigStruct)]
{
// Attributes available to this derive:
#[default]
#[enumerated]
#[var_name]
}
Expand description
This proc macro derives the ConfigStruct
trait for a struct, enabling easy extraction of
fields from environment variables and parsing them to the correct type.
The macro supports the following attributes for struct fields:
default
: Sets a default value for the field. If not provided, the macro will panic if the environment variable is not set.env_var
: Sets the name of the environment variable to use for the field. If not provided, the macro will use the name of the field in uppercase as the environment variable name.enumerated
: Identifies an enum that implements theEnvVar
trait. The macro will parse the environment variable to the enum type.
Example usage:
use env_extract::ConfigStruct;
use env_extract::EnvVar;
#[derive(Debug, EnvVar)]
#[var_name = "DATABASE_TYPE"]
#[panic_on_invalid]
#[case(convert = "lowercase")]
enum DatabaseType {
Postgres,
Mysql,
Sqlite,
}
#[derive(ConfigStruct, Debug)]
struct Config {
db_host: String,
db_port: u16,
use_tls: bool,
#[enumerated]
db_type: DatabaseType,
}
fn main() {
std::env::set_var("DB_HOST", "localhost");
std::env::set_var("DB_PORT", "5432");
std::env::set_var("USE_TLS", "true");
std::env::set_var("DATABASE_TYPE", "postgres");
let config = Config::get();
assert_eq!(config.db_host, "localhost");
assert_eq!(config.db_port, 5432);
assert_eq!(config.use_tls, true);
assert!(matches!(config.db_type, DatabaseType::Postgres));
}
In the example above, the ConfigStruct
trait is derived for the Config
struct, allowing
easy extraction of fields from environment variables. The db_host
, db_port
, and use_tls
fields are extracted as String
, u16
, and bool
types, respectively. The db_type
field is
extracted as an enum type DatabaseType
, which is parsed from the environment variable named
DATABASE_TYPE
and converted to lowercase.