expression

TOML defaults and missing optional values

Define a default for absent required settings and use Option for genuinely optional values. TOML does not have a JSON-style null literal. This example uses external crates; see the staged Cargo manifest. Expected stdout (not executed): 2 true Common mistake: Using null as a TOML value instead of omitting an optional key.

Formal Syntax & Structure

rust syntaxrust
#[serde(default = "function")] ; Option<T>

Working Example

Example Snippetrust
fn main() {    fn default_workers() -> u16 { 2 }    #[derive(serde::Deserialize)]    struct Config { #[serde(default = "default_workers")] workers: u16, label: Option<String> }    let c: Config = toml::from_str("").unwrap();    println!("{} {}", c.workers, c.label.is_none());}
Rust Reference