pub trait FromEnv:
Debug
+ Sized
+ 'static {
type Error: Error + Clone;
// Required methods
fn inventory() -> Vec<&'static EnvItemInfo>;
fn from_env() -> Result<Self, FromEnvErr<Self::Error>>;
// Provided method
fn check_inventory() -> Result<(), Vec<&'static EnvItemInfo>> { ... }
}Expand description
Trait for loading from the environment.
This trait is for structs or other complex objects, that need to be loaded from the environment. It expects that
- The struct is
Sizedand'static. - The struct elements can be parsed from strings.
- Struct elements are at fixed env vars, known by the type at compile time.
As such, unless the env is modified, these are essentially static runtime values. We do not recommend using dynamic env vars.
§FromEnv vs FromEnvVar
While FromEnvVar deals with loading simple types from the environment,
FromEnv is for loading complex types. It builds a struct from the
environment, usually be delegating each field to a FromEnvVar or
FromEnv implementation. FromEnv effectively defines a singleton
configuration object, which is produced by loading many env vars, while
FromEnvVar defines a procedure for loading data from a single
environment variable.
§Implementing FromEnv
Please use the FromEnv derive macro to implement this
trait.
§Note on error types
FromEnv and FromEnvVar are often deeply nested. This means that
error types are often nested as well. To avoid this, we use a single error
type FromEnvVar that wraps an inner error type. This allows us to
ensure that env-related errors (e.g. missing env vars) are not lost in the
recursive structure of parsing errors. Environment errors are always at the
top level, and should never be nested. Do not use FromEnvErr<T> as
the Error associated type in FromEnv.
// Do not do this
impl FromEnv for MyType {
type Error = FromEnvErr<MyTypeErr>;
}
// Instead do this:
impl FromEnv for MyType {
type Error = MyTypeErr;
}Required Associated Types§
Required Methods§
Sourcefn inventory() -> Vec<&'static EnvItemInfo>
fn inventory() -> Vec<&'static EnvItemInfo>
Get the required environment variable names for this type.
§Note
This MUST include the environment variable names for all fields in the struct, including optional vars.
Sourcefn from_env() -> Result<Self, FromEnvErr<Self::Error>>
fn from_env() -> Result<Self, FromEnvErr<Self::Error>>
Load from the environment.
Provided Methods§
Sourcefn check_inventory() -> Result<(), Vec<&'static EnvItemInfo>>
fn check_inventory() -> Result<(), Vec<&'static EnvItemInfo>>
Get a list of missing environment variables.
This will check all environment variables in the inventory, and return a list of those that are non-optional and missing. This is useful for reporting missing environment variables.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.