Context
Context is an important mechanism that allows for different default values, merge strategies, and validation rules to be used, for the same configuration struct, depending on context!
To begin, a context is a struct with a default implementation.
#![allow(unused)]
fn main() {
#[derive(Default)]
struct ExampleContext {
pub some_value: bool,
pub another_value: usize,
}
}
Context must then be associated with a
Config derived struct through the
context attribute field.
#![allow(unused)]
fn main() {
#[derive(Config)]
#[config(context = ExampleContext)]
struct ExampleConfig {
// ...
}
}
And then passed to the
ConfigLoader::load_with_context()
method.
#![allow(unused)]
fn main() {
let context = ExampleContext {
some_value: true,
another_value: 10,
};
let result = ConfigLoader::<ExampleConfig>::new()
.url(url_to_config)?
.load_with_context(&context)?;
}
Refer to the default values, merge strategies, and validation rules sections for more information on how to use context.
Nested configs with another context
A nested config receives its parent’s context, so by default it must declare the
same one. A config from a library can’t know an application’s context, so the context field of
#[setting(nested)] maps the parent’s context to the nested config’s own, with a function from a
reference to one to a reference to the other.
#![allow(unused)]
fn main() {
#[derive(Config)]
#[config(context = AppContext)]
struct AppConfig {
// A library config, whose context is `()`
#[setting(nested, context = schematic::context::unit)]
pub lib: LibConfig,
// A config whose context is part of the application's
#[setting(nested, context = plugin_context)]
pub plugin: PluginConfig,
}
fn plugin_context(context: &AppContext) -> &PluginContext {
&context.plugin
}
}
The mapped context is what the nested config’s own default values, merge strategies, and validation
rules receive. schematic::context::unit passes (), whatever the parent’s context. A
Default of the parent, which has no context to map, gives each nested config the Default of its
own context instead.
Metadata
Alongside the configuration itself, the derive records a little metadata about each
setting, reachable with
Config::settings().
It returns a map keyed by the serde name of each setting, or by position for unnamed ones.
#![allow(unused)]
fn main() {
for (name, setting) in ExampleConfig::settings() {
println!("{name}: {}", setting.type_alias);
if let Some(key) = &setting.env_key {
println!(" reads {key}");
}
if let Some(nested) = &setting.nested {
println!(" has {} nested settings", nested.len());
}
}
}
Each entry carries the setting’s type_alias (the Rust type as written), its env_key, and a
nested map when the setting holds another nested config.
A key derived from an
env_prefixis reported with the container’s own prefix. A parent’s#[setting(nested, env_prefix)]override is applied at runtime, so it isn’t reflected here.