[Go] Load a YAML file into a struct

Created on November 30, 2026

You can read a YAML file and pass its bytes to yaml.Unmarshal from gopkg.in/yaml.v2. The yaml tags match YAML keys to fields in the Go structs. Save this data as sample.yml.

users:
  - name: Tom
    age: 15
  - name: Bob
    age: 30

In your Go module, install the dependency with go get gopkg.in/yaml.v2, then run the following program.

package main

import (
    "fmt"
    "io/ioutil"

    "gopkg.in/yaml.v2"
)

type YamlContent struct {
    Users []User `yaml:"users"`
}

type User struct {
    Name string `yaml:"name"`
    Age  int    `yaml:"age"`
}

func main() {
    f, err := ioutil.ReadFile("./sample.yml")
    if err != nil {
        panic(err.Error())
    }

    yamlContent := &YamlContent{}
    err = yaml.Unmarshal(f, &yamlContent)
    if err != nil {
        panic(err.Error())
    }

    fmt.Printf("%#v", yamlContent)
}
&main.YamlContent{Users:[]main.User{main.User{Name:"Tom", Age:15}, main.User{Name:"Bob", Age:30}}}
Go