---
title: "Rename a YAML key in Go without losing comments"
url: https://recursiveai.org/oneyaml/go/cookbook/rename-yaml-key-keep-comments/
description: "Rename a YAML mapping key in Go without moving its value or losing its comments. See how to detect a name collision before saving."
version: "1.0.0"
---

# Rename a YAML key in Go without losing comments

**oneyaml-go** is a free, open-source YAML library for Go from Recursive AI. MIT or Apache-2.0, no dependencies.

[pkg.go.dev](https://pkg.go.dev/oneyaml.dev/go) · [GitHub](https://github.com/recursive-ai-oss/oneyaml-go) · [Docs](https://recursiveai.org/oneyaml/go/docs/) · [Download example (.zip)](https://recursiveai.org/oneyaml/go/cookbook/rename-yaml-key-keep-comments/rename-yaml-key-keep-comments.zip)

Call `doc.Rename("/port", "httpPort")` to keep the comment. The first argument is the path (pointer) to the old key, such as `/service/port` for a nested key.

```shell
go get oneyaml.dev/go
```

Requires Go 1.24+. Run in a Go module.

```go
package main

import (
	"fmt"
	"oneyaml.dev/go"
)

func main() {
	input := "port: 80 # public port\n"
	doc, err := oneyaml.Parse([]byte(input))
	if err != nil {
		panic(err)
	}
	err = doc.Rename("/port", "httpPort")
	if err != nil {
		panic(err)
	}
	fmt.Print(doc)
}
```

Unzip [the example](https://recursiveai.org/oneyaml/go/cookbook/rename-yaml-key-keep-comments/rename-yaml-key-keep-comments.zip), then `go run .`.

```text
httpPort: 80 # public port
```

Printing `doc` gives the same YAML text as `doc.Bytes()`.

## The full program

```go
package main

import (
	"errors"
	"fmt"
	"oneyaml.dev/go"
)

func main() {
	const input = `service:
  # Public listener
  port: 80 # public port
  host: example.org
`
	doc, err := oneyaml.Parse([]byte(input))
	if err != nil {
		panic(err)
	}
	err = doc.Rename("/service/port", "httpPort")
	if err != nil {
		panic(err)
	}
	err = doc.Rename("/service/httpPort", "host")
	if !errors.Is(err, oneyaml.ErrKeyExists) {
		panic(fmt.Sprintf("expected a key collision, got %v", err))
	}
	fmt.Println("Collision rejected")
	fmt.Print(doc)
}
```

```text
Collision rejected
service:
  # Public listener
  httpPort: 80 # public port
  host: example.org
```

The download renames a nested key, then tries to rename it to `host`. If the new name already exists in that mapping, `Rename` returns `ErrKeyExists` and leaves the YAML unchanged.

## Variations

**A name that looks like a number.** Replace the `Rename` call’s assignment with this line:

```go
err = doc.Rename("/port", "8080")
```

```text
'8080': 80 # public port
```

**Read a YAML file and save the renamed key.** Save this as `config.yaml`, add `"os"` to the imports in the snippet at the top, and replace everything inside `main` with the code below.

```yaml
service:
  # Public listener
  port: 80 # public port
```

```go
input, err := os.ReadFile("config.yaml")
if err != nil {
	panic(err)
}
doc, err := oneyaml.Parse(input)
if err != nil {
	panic(err)
}
err = doc.Rename("/service/port", "httpPort")
if err != nil {
	panic(err)
}
err = os.WriteFile("updated.yaml", doc.Bytes(), 0644)
if err != nil {
	panic(err)
}
fmt.Print(doc)
```

This prints the contents it writes to `updated.yaml`. The input file stays unchanged.

```text
service:
  # Public listener
  httpPort: 80 # public port
```

## Related recipes

- [Edit a YAML file and keep its comments](https://recursiveai.org/oneyaml/go/cookbook/edit-yaml-keep-comments/)
- [Add a comment to a YAML file](https://recursiveai.org/oneyaml/go/cookbook/add-comment-to-yaml/)

## The short answer

Parse the YAML into a `Document`, then call `Rename` with a pointer to the **old** entry and the new key’s text. The path selects the entry; the second argument names it but doesn’t move it. On success, `doc.Bytes()` holds the changed YAML. On a collision, keep the original name or choose one that’s unused in that mapping.

## How do you rename a nested YAML key without losing comments?

Think of the pointer as the path from the top of the document. In the download, `/service/port` selects `port` within the `service` mapping. After the edit, the path is `/service/httpPort`. The comment above the entry and the comment after its value both stay where they were. Unlike deleting a key and adding a new one, `Rename` keeps the entry in the same position between its neighbors. The new name must be unique within that map, not across the entire file. A `host` under a different parent doesn’t block the rename.

If a path component comes from user input or configuration, build it with `oneyaml.Pointer` rather than joining names with `/`. A slash can be part of a key: `/service/api~1port` means the entry `api/port` under `service`, not a deeper path. This escaping rule applies to the old key’s pointer, not to the new name, which is passed as literal text. See the [editing guide](https://recursiveai.org/oneyaml/go/docs/editing/#renaming-a-key) for the errors you can handle, including a pointer that lands on a list item rather than a mapping entry.

## How do you edit a YAML file without losing its original formatting?

Use the parsed document rather than converting the YAML into a Go map and serializing it again. A map holds keys and values but has no place for the comments, blank lines, or quote styles from the input. A document edit can change the key text without reconstructing the rest of the file. `Rename` also keeps the key’s original quoting when that style can represent the new name. For example, renaming `port` to `8080` adds quotes so the new key is a string, not a number.

`Rename` changes the in-memory document, not the file you read. If this is part of a configuration tool, check for errors before writing `doc.Bytes()` to a file. Keeping the write separate also lets you print or review the change before replacing the input.
