Recursive AI

Inline an embedded struct in Go YAML

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

Use yaml:",inline" to keep shared fields in a Go type without adding a level to the YAML.

Terminal
go get oneyaml.dev/go
GO
package main
 
import (
	"fmt"
 
	yaml "oneyaml.dev/go"
)
 
type Base struct {
	Port int `yaml:"port"`
}
 
type Config struct {
	Base `yaml:",inline"`
	Name string `yaml:"name"`
}
 
func main() {
	input := []byte("port: 8080\nname: api\n")
	var cfg Config
	err := yaml.Unmarshal(input, &cfg)
	if err != nil {
		panic(err)
	}
	fmt.Println("Port:", cfg.Port)
	output, err := yaml.Marshal(cfg)
	if err != nil {
		panic(err)
	}
	fmt.Print(string(output))
}

Unzip the example, then go run ..

Text
Port: 8080
port: 8080
name: api

Requires Go 1.24 or later. Run go get inside a Go module.

Unmarshal reads the top-level port into cfg.Base.Port, also accessible as cfg.Port. Marshal writes it at the top level again. If you’re switching from the v3 package, yaml:",inline" flattens embedded structs the same way. A field with an incompatible value, such as port: api, returns an error instead of a port number.

Variations

To group the shared fields below base, change the tag and the input together:

GO
type Config struct {
    Base `yaml:"base"`
    Name string `yaml:"name"`
}
YAML
base:
  port: 8080
name: api

cfg.Port still works in Go, but the marshaled port now appears inside base.

The short answer

Put yaml:",inline" on the embedded struct field. oneyaml-go reads the embedded type’s keys from the surrounding mapping and writes them back at the same level. Here, Base.Port is still declared in Base, but the YAML has a port key beside name, not a base mapping. The comma matters: inline is an option, not the field name.

How do you choose between inline and nested YAML fields?

Choose by the shape a reader expects. If several kinds of service share a top-level port, you can reuse Base in Go without changing those YAML files. If port belongs to a distinct group and the file already spells it as base.port, use a named mapping such as yaml:"base" instead. The variation shows that the Go expression cfg.Port is the same for both shapes: Go embedding promotes field selectors, while the YAML tag controls where values are read and written.

What if the embedded struct and the parent use the same YAML key?

The shallower field wins. If you add Other int to Config with the tag yaml:"port", Unmarshal fills Other instead of Base.Port, and Marshal writes Other under port. The pinned field-selection rules also drop a name if competing fields at the same depth tie. Give the fields different YAML keys or put them in separate mappings if you want to keep both values.

All oneyaml Go recipes