---
title: "Set a YAML default in Rust only when the key is missing"
url: https://recursiveai.org/oneyaml/rust/cookbook/create-missing-yaml-key/
description: "Use the Rust YAML entry API to add a default for an absent key, leaving explicitly configured values and nulls untouched."
version: "1.2.0"
---

# Set a YAML default in Rust only when the key is missing

**oneyaml** is a free, open-source YAML library for Rust from Recursive AI. MIT or Apache-2.0, no unsafe code.

[crates.io](https://crates.io/crates/oneyaml) · [GitHub](https://github.com/recursive-ai-oss/oneyaml-rust) · [Docs](https://recursiveai.org/oneyaml/rust/docs/) · [Download example (.zip)](https://recursiveai.org/oneyaml/rust/cookbook/create-missing-yaml-key/create-missing-yaml-key.zip)

Use `or_insert` to fill in `workers` without replacing the configured `port`.

```shell
cargo add oneyaml
```

```rust
use oneyaml::Document;

fn main() {
    let yaml = "port: 8080 # explicit\n";
    let mut doc = Document::parse(yaml)
        .expect("valid YAML");
    for (key, default) in [
        ("port", 80), ("workers", 4),
    ] {
        doc.root_mut().expect("root")
            .entry(key).expect("mapping entry")
            .or_insert(default).expect("default");
    }
    print!("{doc}");
}
```

Unzip [the example](https://recursiveai.org/oneyaml/rust/cookbook/create-missing-yaml-key/create-missing-yaml-key.zip), then `cargo run`.

Requires Rust 1.85 or later. The snippet prints the updated YAML:

```text
port: 8080 # explicit
workers: 4
```

## The full program

The program tries the same operation with `workers: null`.

```rust
use oneyaml::Document;

fn main() {
    let yaml = "port: 8080 # explicit\n";
    let mut doc = Document::parse(yaml)
        .expect("valid YAML");
    for (key, default) in [
        ("port", 80), ("workers", 4),
    ] {
        doc.root_mut().expect("root")
            .entry(key).expect("mapping entry")
            .or_insert(default).expect("default");
    }
    print!("{doc}");

    // A null value is still an explicit entry.
    let mut doc = Document::parse("workers: null\n").expect("valid YAML");
    let entry = doc.root_mut().expect("root")
        .entry("workers").expect("mapping entry");
    assert!(entry.is_occupied());
    entry.or_insert(4).expect("default");
    print!("With explicit null:\n{doc}");
}
```

`cargo run` prints:

```text
port: 8080 # explicit
workers: 4
With explicit null:
workers: null
```

## Related recipes

- [Edit YAML and keep its comments](https://recursiveai.org/oneyaml/rust/cookbook/edit-yaml-keep-comments/)
- [Parse YAML into Rust structs](https://recursiveai.org/oneyaml/rust/cookbook/parse-yaml-into-structs/)
- [Read YAML anchors, aliases, and merge keys](https://recursiveai.org/oneyaml/rust/cookbook/anchors-aliases-merge-keys/)

## The short answer

Use `entry(key)` on the editable mapping and call `or_insert(default)`. If the key is present in that mapping, you get a handle to the existing value without replacing it. Otherwise the method creates the missing entry. The example leaves `port: 8080 # explicit` as written and adds `workers: 4`.

## Does a YAML default replace an explicit null?

Not with `or_insert`. The test is for membership in the mapping, not whether the current value looks empty or false. `workers: null` is an explicit entry, as are `workers: 0` and `workers: false`. The method doesn’t validate whether the existing value is meaningful for your application. If the target node is a scalar or list instead of a mapping, `entry` returns `EditError::NotAMapping`. Treating null as a request to use a default would be a separate rule.

[entry(key)](https://github.com/recursive-ai-oss/oneyaml-rust/blob/14445615f5a5b2895fdaa1da7719584ef15d9d6b/crates/oneyaml/src/document/edit.rs#L7932-L7953) checks keys written directly in the selected mapping. A value available only through a YAML merge key (`<<`) doesn’t count as a local entry here. Inserting a local key can therefore override an inherited value. If you want to retain inherited defaults as well, decide whether the key is missing using a merge-aware read before editing.

## How do you set default values when reading YAML in Rust?

There are two different results you might want. To fill a field in a deserialized Rust struct, use [Serde’s `default` field attribute](https://serde.rs/field-attrs.html#default). That affects the Rust value your program receives; it doesn’t add a key to the YAML text. This recipe edits a `Document` because the desired result is the updated YAML itself. That matters for a settings-file upgrade: the new key can appear in the output while the operator’s existing value and inline note remain exactly as written.
