---
title: "Rename a YAML anchor and its aliases in Rust"
url: https://recursiveai.org/oneyaml/rust/cookbook/rename-yaml-anchor-and-aliases/
description: "Rename a YAML anchor in Rust with Document::set_anchor. Update the aliases that point to it without reformatting the file or losing comments."
version: "1.2.0"
---

# Rename a YAML anchor and its aliases 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/rename-yaml-anchor-and-aliases/rename-yaml-anchor-and-aliases.zip)

`set_anchor` renames `&old` and the `*old` references to it in one edit.

```shell
cargo add oneyaml
```

In a `main` that returns `Result<(), Box<dyn std::error::Error>>`:

```rust
use oneyaml::Document;

let yaml = "base: &old 'blue'\nweb: *old\n";
let mut doc = Document::parse(yaml)?;
let base = doc.get_path("base")
    .ok_or("missing base")?.id();
doc.set_anchor(base, Some("color"))?;
print!("{doc}");
```

[The example](https://recursiveai.org/oneyaml/rust/cookbook/rename-yaml-anchor-and-aliases/rename-yaml-anchor-and-aliases.zip) is the full program below: unzip it and `cargo run`. To run only the code above, paste it into src/main.rs of a new `cargo new example` project and `cargo run`.

The snippet prints:

```yaml
base: &color 'blue'
web: *color
```

## The full program

The download adds a second alias and checks that both resolve to the renamed node. The input has a comment, a blank line and a single-quoted value, all of which stay as written.

```rust
use oneyaml::Document;

type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

fn main() -> Result<()> {
    let yaml = "base: &old 'blue' # shared\n\nweb: *old\njobs: *old\n";
    let mut doc = Document::parse(yaml)?;
    let anchor = doc.get_path("base").ok_or("missing base")?.id();
    let renamed = doc.set_anchor(anchor, Some("color"))?;
    print!("{doc}");

    for key in ["web", "jobs"] {
        let alias = doc.get_path(key).ok_or("missing alias")?;
        let target = alias.alias_target().ok_or("unresolved alias")?;
        assert_eq!(target.id(), renamed);
        let color = target.as_str().ok_or("expected a string")?;
        println!("{key} resolves to {color}");
    }
    Ok(())
}
```

`cargo run` prints the edited YAML, then the two results from resolving the aliases:

```text
base: &color 'blue' # shared

web: *color
jobs: *color
web resolves to blue
jobs resolves to blue
```

If an anchor with the proposed name already exists in the document, `set_anchor` returns `EditError::DuplicateAnchor`; choose a name that isn’t in use.

## Variations

**Count the aliases before renaming.** Insert this just before `set_anchor` in the full program:

```rust
println!("{} aliases", doc.aliases_of(anchor)?.len());
```

This adds `2 aliases` before the edited YAML.

## Related recipes

- [Read YAML anchors and merge keys in Rust](https://recursiveai.org/oneyaml/rust/cookbook/anchors-aliases-merge-keys/)
- [Edit YAML without losing comments in Rust](https://recursiveai.org/oneyaml/rust/cookbook/edit-yaml-keep-comments/)

## The short answer

With oneyaml-rust, find the node carrying the anchor and pass its ID to `doc.set_anchor(id, Some("new_name"))`. Pass the bare name, without an `&` or `*`. The edit renames the anchor and every alias that resolves to that node, so callers that read an alias still get the same value. It does not rename the mapping key, `base` in this example.

## How do YAML aliases know which anchor to use?

An alias refers to the most recent preceding anchor of that name in the same document, as defined in the [YAML specification](https://yaml.org/spec/1.2.2/#3222-anchors-and-aliases). If a file uses the same anchor name twice, an alias between the two definitions still refers to the first definition. An alias after the second definition refers to that second node. Renaming one definition with `set_anchor` updates only the references to that node. Changing every matching string in the file would miss this distinction and could also change comments or quoted text.

Use `alias_target()` to check where a reference goes. It returns `None` if the node isn’t a resolved alias. In the full program, the target ID for each alias matches the ID returned by `set_anchor`; checking only the alias name would verify the spelling, not where the alias points.

## Can I remove a YAML anchor if aliases still use it?

In oneyaml-rust, `set_anchor(id, None)` returns `EditError::AnchorInUse` if the node still has aliases. Use `aliases_of(id)` to find those references first. If the references must stay, rename the anchor instead of removing it. The operation also refuses a new name that would make a previously unresolved alias point to this node. These checks keep a rename from changing which values the references resolve to.
