or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

basic-operations.mdcustom-serialization.mdindex.mdnode-manipulation.mdstreaming-operations.md
tile.json

basic-operations.mddocs/

Basic YAML Operations

Core functions for simple YAML encoding and decoding. Use these for straightforward marshaling and unmarshaling of YAML documents.

Marshal

Serializes a Go value into a YAML document.

func Marshal(in interface{}) (out []byte, err error)

Parameters

  • in (interface{}) - The value to marshal. Accepts maps, pointers to structs, strings, ints, and other Go types.

Returns

  • out ([]byte) - The serialized YAML document as a byte slice
  • err (error) - Error if marshaling fails, nil otherwise

Behavior

  • Struct fields must be exported (uppercase first letter) to be marshaled
  • Fields are marshaled using the field name lowercased as the default key
  • Custom keys can be defined via yaml struct tags
  • Zero-valued fields are included by default (use omitempty tag to exclude)
  • Maps, pointers, structs, slices, and primitive types are supported

Usage Example

package main

import (
    "fmt"
    "log"
    "gopkg.in/yaml.v3"
)

type Config struct {
    Name    string
    Port    int `yaml:"port"`
    Enabled bool `yaml:"enabled,omitempty"`
}

func main() {
    config := Config{
        Name: "MyService",
        Port: 8080,
        Enabled: true,
    }

    data, err := yaml.Marshal(&config)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%s", data)
    // Output:
    // name: MyService
    // port: 8080
    // enabled: true
}

Struct Tag Format

`yaml:"[<key>][,<flag1>[,<flag2>]]"`

Supported flags:

  • omitempty - Omit field if zero value
  • flow - Use flow style for structs, sequences, and maps
  • inline - Inline struct or map fields into parent struct
  • Use key "-" to ignore the field

Example with Tags

type Person struct {
    Name     string            `yaml:"name"`
    Age      int               `yaml:"age,omitempty"`
    Hobbies  []string          `yaml:"hobbies,flow"`
    Metadata map[string]string `yaml:",inline"`
    Internal string            `yaml:"-"`
}

p := Person{
    Name:    "Alice",
    Age:     0,  // Will be omitted due to omitempty
    Hobbies: []string{"reading", "coding"},
    Metadata: map[string]string{"role": "developer"},
    Internal: "not exported",
}

data, _ := yaml.Marshal(&p)
fmt.Printf("%s", data)
// Output:
// name: Alice
// hobbies: [reading, coding]
// role: developer

Unmarshal

Decodes the first YAML document found within a byte slice and assigns values into a Go variable.

func Unmarshal(in []byte, out interface{}) (err error)

Parameters

  • in ([]byte) - The YAML document as a byte slice
  • out (interface{}) - Pointer to the variable where decoded values will be stored. Must not be nil.

Returns

  • err (error) - Returns *yaml.TypeError if one or more fields cannot be decoded due to type mismatches. Unmarshaling continues partially. Returns nil on success.

Behavior

  • Accepts maps and pointers (to struct, string, int, etc.) as out values
  • Initializes internal pointers within structs if necessary
  • The out parameter must not be nil
  • Struct fields must be exported (uppercase first letter) to be unmarshaled
  • Fields are matched using the field name lowercased by default
  • Custom keys can be defined via yaml struct tags
  • Type mismatches result in partial unmarshaling with a *yaml.TypeError containing all errors

Usage Example

package main

import (
    "fmt"
    "log"
    "gopkg.in/yaml.v3"
)

type Config struct {
    Name     string
    Port     int      `yaml:"port"`
    Database struct {
        Host string
        Port int
    }
}

func main() {
    data := []byte(`
name: MyService
port: 8080
database:
  host: localhost
  port: 5432
`)

    var config Config
    err := yaml.Unmarshal(data, &config)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Name: %s\n", config.Name)
    fmt.Printf("Port: %d\n", config.Port)
    fmt.Printf("DB: %s:%d\n", config.Database.Host, config.Database.Port)
}

Unmarshaling into Maps

data := []byte(`
name: Alice
age: 30
active: true
`)

var result map[string]interface{}
err := yaml.Unmarshal(data, &result)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("%v\n", result)
// Output: map[active:true age:30 name:Alice]

Error Handling

type Config struct {
    Port int
}

data := []byte(`port: "not a number"`)

var config Config
err := yaml.Unmarshal(data, &config)
if err != nil {
    if typeErr, ok := err.(*yaml.TypeError); ok {
        for _, errMsg := range typeErr.Errors {
            fmt.Println("Unmarshal error:", errMsg)
        }
    }
}

Struct Field Tag Options

Both Marshal and Unmarshal respect struct field tags for customization:

Key Customization

type T struct {
    Field int `yaml:"custom_name"`
}
// YAML key will be "custom_name" instead of "field"

Omit Empty Values

type T struct {
    Field int `yaml:"field,omitempty"`
}
// Field is omitted from output if it has zero value

The omitempty flag respects the IsZeroer interface. If a struct implements IsZero() bool, that method determines whether the field is omitted.

Flow Style

type T struct {
    Items []int `yaml:"items,flow"`
}
// Output: items: [1, 2, 3]
// Instead of:
// items:
//   - 1
//   - 2
//   - 3

Inline Fields

type Metadata struct {
    CreatedAt string
    UpdatedAt string
}

type Document struct {
    Title    string
    Metadata Metadata `yaml:",inline"`
}

// The Metadata fields become top-level keys:
// title: Example
// createdat: 2023-01-01
// updatedat: 2023-01-02

Ignore Fields

type T struct {
    Public   string
    Internal string `yaml:"-"`
}
// Internal field is completely ignored during marshaling/unmarshaling

Type Support

Supported Types

  • Primitives: string, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, bool
  • Complex types: structs, maps, slices, arrays
  • Pointers: pointers to any supported type
  • Interfaces: empty interface and typed interfaces
  • Special: time.Time (automatically handled)

Map Keys

Map keys must be comparable types. Common map types:

map[string]interface{}    // Most flexible
map[string]string         // String values only
map[interface{}]interface{} // Any key/value type

Nil and Zero Values

  • Nil pointers, slices, and maps are encoded as null in YAML
  • Zero values are included in output unless omitempty is used
  • When unmarshaling, nil pointers within structs are automatically initialized

Notes

  • For processing multiple YAML documents or streaming operations, use Streaming YAML Operations
  • For custom marshaling/unmarshaling behavior, implement the Marshaler/Unmarshaler interfaces (see Custom Type Serialization)
  • For fine-grained control over YAML structure, use Node Manipulation