Skip to content

Edit a value

Change an existing scalar

err := doc.Set("server.port", 9090)

The node is mutated in place, so its inline comment and quoting style survive:

port: 8080   # the port we bind to
# becomes
port: 9090   # the port we bind to

A value that was quoted stays quoted; one that was bare stays bare.

doc.Set("name", "after")   // quoted: "before"  →  quoted: "after"
doc.Set("kind", "after")   // kind: before      →  kind: after

Set accepts strings, booleans, all integer and float widths, and maps and slices for whole subtrees.

Create a key

Setting a path that does not exist creates it, appended to the deepest existing ancestor. Appending rather than inserting is deliberate: existing keys keep their comments and their order.

err := doc.Set("server.timeout", "30s")
server:
  host: localhost   # where we bind
  port: 8080
  timeout: 30s      # ← added here

Missing intermediate mappings are synthesised:

err := doc.Set("server.tls.cert", "/etc/cert.pem")
server:
  host: localhost
  tls:
    cert: /etc/cert.pem

Replace a subtree

Passing a map replaces the addressed node wholesale — keys absent from the map are gone.

err := doc.Set("avatars.matt", map[string]any{
    "likeness": "a bearded developer",
})

You own what you replace

A subtree replaced from a Go value cannot keep what the Go value does not carry. Comments inside that subtree, anchors, and block scalar styles are lost, because nothing in the map describes them.

For a targeted change, address the leaf directly (avatars.matt.likeness) rather than replacing its parent. Reach for subtree replacement when you genuinely own the whole value.

What cannot be created

A path that runs through a scalar is refused rather than silently rewriting it:

// given "a: 1"
err := doc.Set("a.b.c", "value")   // ErrNotFound: "a" is not a mapping

Creating it would mean destroying a, which you did not ask for.

Errors worth branching on

switch {
case errors.Is(err, yamldoc.ErrNotFound):     // path does not resolve
case errors.Is(err, yamldoc.ErrInvalidPath):  // malformed path expression
case errors.Is(err, yamldoc.ErrUnsupported):  // document cannot be edited safely
}