Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Default values

In Schematic, there are 2 forms of default values:

  • The first is applied through the partial configuration, is defined with the #[setting] attribute, and is the layer below every other.
  • The second is on the final configuration itself, and uses the Default trait to generate the final value if none was provided. This acts more like a fallback. To fail instead, mark the setting as required.

To define a default value, use the #[setting(default)] attribute. The default attribute field accepts any expression of the setting’s type, like a number, a boolean, an array, tuple, or struct literal, a path that names a value, or a function, method, or macro call. A string converts into the setting’s type, and a bare path in snake_case names a handler function.

#![allow(unused)]
fn main() {
#[derive(Config)]
struct AppConfig {
	#[setting(default = "/")]
	pub base: String,

	#[setting(default = 3000)]
	pub port: usize,

	#[setting(default = true)]
	pub secure: bool,

	#[setting(default = vec!["localhost".into()])]
	pub allowed_hosts: Vec<String>,

	#[setting(default = LevelFilter::Debug)]
	pub log_level: LevelFilter,

	#[setting(default = Retry { attempts: 3, backoff: 500 })]
	pub retry: Retry,

	#[setting(default = PathBuf::from("/etc").join("app"))]
	pub config_dir: PathBuf,
}
}

A string that fails to convert, or a handler function that fails, is an error naming the setting, like Invalid default value for port. invalid digit found in string.

Paths: value or function?

A bare path is ambiguous — LevelFilter::Debug names a value, while find_unused_port names a handler function to call. Nothing at compile time can tell them apart, so Schematic goes by Rust’s naming conventions:

Last segment of the pathTreated asExample
Starts uppercaseA valueLevelFilter::Debug
Starts lowercaseA handler functionfind_unused_port

That covers enum variants, unit structs, and constants on one side, and functions on the other, since a name breaking those conventions would already be earning a compiler lint.

A handler function that must keep a non-conventional name can be reached through a snake_case wrapper, or called directly with default = my_wrapper() when it needs no context.

Enum variants

For enums, the default field marks which variant to use as the default. A unit variant holds no value, so default takes none, or a boolean.

#![allow(unused)]
fn main() {
#[derive(Config)]
enum Host {
	#[setting(default)]
	Local,
	Remote(HostConfig),
}
}

A variant that holds a single value can take a value as well, which marks it as the default and is what it holds. It accepts anything a setting’s default does, including a handler function that returns the value. Without one, the variant holds the default of its type.

#![allow(unused)]
fn main() {
#[derive(Config)]
enum Compress {
	Fast,
	Best,
	#[serde(untagged)]
	#[setting(default = true)]
	Enabled(bool),
}
}

A value can’t be provided for a variant holding several values, or a nested configuration, which sources its defaults from its own settings.

A named variant takes no value either, as each of its fields takes a default of its own. They’re applied whenever the variant is picked, not only when it’s the default, as the defaults are read for the variant the sources picked, so a source that picks Url below gets a timeout of 30.

#![allow(unused)]
fn main() {
#[derive(Config)]
enum Host {
	#[setting(default)]
	Local,
	Url {
		address: String,
		#[setting(default = 30)]
		timeout: u32,
	},
}
}

Handler function

If you need more control or need to calculate a complex value, you can pass a reference to a function to call. This function receives the context as the first argument, and can return an optional value. If None is returned, the Default value will be used instead.

#![allow(unused)]
fn main() {
fn find_unused_port(ctx: &Context) -> DefaultValueResult<usize> {
	let port = do_find()?;

	Ok(Some(port))
}

#[derive(Config)]
struct AppConfig {
	#[setting(default = find_unused_port)]
	pub port: usize,
}
}

Context handling

If you’re not using context, you can use () as the context type, or rely on generic inferrence.

#![allow(unused)]
fn main() {
fn using_unit_type(_: &()) -> DefaultValueResult<usize> {
	// ...
}

fn using_generics<C>(_: &C) -> DefaultValueResult<usize> {
	// ...
}
}