---
title: "Warn on duplicate YAML keys in Rust"
url: https://recursiveai.org/oneyaml/rust/cookbook/warn-on-duplicate-yaml-keys/
description: "Read a legacy YAML mapping in Rust with last-value-wins settings, print the duplicate key warning, and see what happens with the strict default."
version: "1.2.0"
---

# Warn on duplicate YAML keys in Rust

**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/warn-on-duplicate-yaml-keys/warn-on-duplicate-yaml-keys.zip)

For legacy YAML, keep the last value and print a warning for each duplicate.

```shell
cargo add oneyaml
```

```rust
use oneyaml::{DuplicateKeys, Settings, Value};

fn main() -> Result<(), oneyaml::Error> {
    let yaml = "workers: 2\nworkers: 4\n";
    let settings = Settings::new()
        .duplicate_keys(DuplicateKeys::LastWins);
    let (config, warnings): (Value, _) =
        oneyaml::from_str_with_diagnostics(
            yaml, &settings)?;
    println!("workers: {}", config["workers"]
        .as_i64().expect("integer worker count"));
    for warning in warnings {
        println!("{}: {}",
            warning.code, warning.message);
    }
    Ok(())
}
```

Unzip [the example](https://recursiveai.org/oneyaml/rust/cookbook/warn-on-duplicate-yaml-keys/warn-on-duplicate-yaml-keys.zip), then `cargo run`.

Requires Rust 1.85 or later.

```text
workers: 4
Y1014: duplicate key `workers`: the last value wins
```

## The full program

The full example reads the same input twice: first with last-wins warnings, then with the default settings. Other parsing errors can still stop a last-wins read; warnings collected before a failure are available on `Error::warnings()`.

```rust
use oneyaml::{DuplicateKeys, Settings, Value};

fn main() -> Result<(), oneyaml::Error> {
    let yaml = "workers: 2\nworkers: 4\n";
    let settings = Settings::new()
        .duplicate_keys(DuplicateKeys::LastWins);
    let (config, warnings): (Value, _) =
        oneyaml::from_str_with_diagnostics(
            yaml, &settings)?;
    println!("workers: {}", config["workers"]
        .as_i64().expect("integer worker count"));
    for warning in warnings {
        println!("{}: {}",
            warning.code, warning.message);
    }

    let err = oneyaml::from_str::<Value>(yaml)
        .expect_err("duplicate workers key");
    println!("{}: {}", err.code(), err);
    Ok(())
}
```

`cargo run` prints:

```text
workers: 4
Y1014: duplicate key `workers`: the last value wins
Y1013: duplicate key `workers` (2:1)
```

## Variations

To print only duplicate-key warnings, replace the `for` loop above with this one.

```rust
for warning in warnings.into_iter().filter(|warning| {
    warning.code == oneyaml::code::DUPLICATE_KEY_LAST_WINS
}) {
    println!("{}: {}", warning.code, warning.message);
}
```

## Related recipes

- [Show YAML errors with line and column](https://recursiveai.org/oneyaml/rust/cookbook/errors-with-line-and-column/)
- [Read YAML without a schema](https://recursiveai.org/oneyaml/rust/cookbook/read-yaml-without-a-schema/)

## The short answer

Set `DuplicateKeys::LastWins` on `Settings` and call `from_str_with_diagnostics`. You get the parsed value and a list of warnings. In the example, the two `workers` keys don’t both survive: `workers: 4` wins, and `Y1014` tells you why. Keep the strict default if the files can be corrected before they’re read.

## What are duplicate keys in YAML?

Two keys are duplicates when they identify the same entry in the same mapping. The [YAML 1.2.2 specification](https://yaml.org/spec/1.2.2/#3211-nodes) requires keys within a mapping to be unique. Two separate mappings can each have a `workers` key without conflict. In the example they’re at the same level in the same mapping, so a strict read rejects the file. Last-wins is an opt-in compatibility setting, not a way to combine the values of two entries or a rule that YAML itself imposes.

If `workers: 2` was set early in the file and `workers: 4` was added later, a successful read alone wouldn’t tell the operator that one setting got replaced. Print the warning to the same place you report other configuration problems, or surface it before the operator saves the normalized configuration. Fix the duplicate at the source rather than depending on its order indefinitely.

## How do you detect duplicate YAML keys without rejecting the file?

The [diagnostics API](https://github.com/recursive-ai-oss/oneyaml-rust/blob/14445615f5a5b2895fdaa1da7719584ef15d9d6b/crates/oneyaml/src/de/api.rs#L171-L195) returns all kinds of warnings, not just duplicates. It returns them in source order up to `Limits::max_diagnostics`, then adds a summary if more warnings were suppressed. If you’re routing only duplicate warnings to a particular message or counter, identify them by `code::DUPLICATE_KEY_LAST_WINS`, not by matching the English message. Use the diagnostics-returning call: `from_str_with` uses the settings but [discards warnings from a successful read](https://github.com/recursive-ai-oss/oneyaml-rust/blob/14445615f5a5b2895fdaa1da7719584ef15d9d6b/crates/oneyaml/src/de/api.rs#L198-L205).

You can deserialize into a struct instead of `Value`. The liberal policy isn’t limited to duplicate keys that appear in the output type: the [pinned ignored-content example](https://github.com/recursive-ai-oss/oneyaml-rust/blob/14445615f5a5b2895fdaa1da7719584ef15d9d6b/crates/oneyaml/tests/serde_ignored.rs#L142-L153) reads a known field and still warns about a duplicate nested inside an unknown field. That is useful when some parts of an older configuration are no longer used but you still want to tell its author what to clean up.
