---
title: "Reject duplicate YAML mapping keys in Rust"
url: https://recursiveai.org/oneyaml/rust/cookbook/reject-duplicate-yaml-keys/
description: "Reject duplicate YAML keys even when reading into a Rust HashMap, and locate both definitions with the parser’s diagnostic."
version: "1.2.0"
---

# Reject duplicate YAML mapping 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/reject-duplicate-yaml-keys/reject-duplicate-yaml-keys.zip)

Use the default reader to reject a repeated key before it can overwrite a setting, even when your Rust target is a `HashMap`.

```shell
cargo add oneyaml
```

```rust
type Config = std::collections::HashMap<
    String, u16,
>;
fn main() {
    let yaml = "port: 8080\nport: 9090";
    match oneyaml::from_str::<Config>(yaml) {
        Ok(config) => println!("{config:?}"),
        Err(err) => println!("{err}"),
    }
}
```

Paste the code above into src/main.rs of a new `cargo new example` project and `cargo run`, or unzip [the example](https://recursiveai.org/oneyaml/rust/cookbook/reject-duplicate-yaml-keys/reject-duplicate-yaml-keys.zip) and `cargo run`.

Requires Rust 1.85 or later. The example prints:

```text
duplicate key `port` (2:1)
```

In an application, return the error to the caller instead of continuing with a partly read configuration.

## Variations

### Set the rejection policy explicitly

Replace the `match` in `main` with this block to pass the strict policy explicitly. It prints the same error as the default reader.

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

let settings = Settings::new()
    .duplicate_keys(DuplicateKeys::Error);
match oneyaml::from_str_with::<Config>(yaml, &settings) {
    Ok(config) => println!("{config:?}"),
    Err(err) => println!("{err}"),
}
```

### Show both definitions

Replace the `Err` arm in `main` with this one. The rendered diagnostic shows `Y1013`, points at line 2, and labels line 1 “first defined here.”

```rust
Err(err) => println!("{}", err.render(yaml)),
```

## Related recipes

- [Show YAML errors with line and column](https://recursiveai.org/oneyaml/rust/cookbook/errors-with-line-and-column/)
- [Warn on duplicate YAML keys in legacy files](https://recursiveai.org/oneyaml/rust/cookbook/warn-on-duplicate-yaml-keys/)

## The short answer

Use `oneyaml::from_str::<HashMap<String, u16>>` with the default settings. oneyaml-rust rejects duplicate keys during YAML deserialization; there’s no need to try to recover overwritten entries from the resulting Rust map. On the two `port` lines above, it returns an error rather than choosing either `8080` or `9090`. If you already pass your own settings, check that they use `DuplicateKeys::Error`.

## Does YAML allow duplicate mapping keys?

No. The [YAML specification](https://yaml.org/spec/1.2.2/#3211-nodes) requires unique keys inside each mapping. That’s a rule about the mapping, not the whole file. Two services can each have a `port` field because each service is a separate mapping. Two `port` entries in a single service are duplicates even when their values agree.

The important distinction is between checking keys as the parser reads them and examining a map after loading. After loading, you can’t tell from a single `port` entry whether it came from one line or whether a reader kept one of two. Check the source through the parser every time you load the file, including when your target is a typed map rather than a generic YAML value.

## How can I find the duplicate key in a YAML file?

The short error identifies the repeated key and the location of its second definition. To help someone fix the input, call `err.render(yaml)` with the original YAML text. It includes the error code (`Y1013`) and shows the first definition next to the repeated one. Keep the full text if you plan to render the error; reserializing a map won’t give you the original lines.

If an old producer sends files you can’t fix, last-value-wins is a separate choice, not a requirement of deserializing into a `HashMap`. The [duplicate-key documentation](https://recursiveai.org/oneyaml/rust/docs/migrating-from-serde-yaml/#duplicate-keys) shows how to opt out of rejection: `DuplicateKeys::LastWins` keeps the last value and records `Y1014`. Keep rejection as the default for configuration you control, so an accidentally repeated setting can’t take effect silently.
