Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

1 snippets
  • Parsing YAML Files in Go Without a Struct Definition

    package main
    
    import (
     "fmt"
     "os"
    
     "gopkg.in/yaml.v3"
    )
    
    func main() {
        dataMap := make(map[string]interface{})
        yamlFile, err := os.ReadFile("example.yaml")
     
        if err != nil {
            panic(err)
        }
    
        err = yaml.Unmarshal(yamlFile, dataMap)
        
        if err != nil {
            panic(err)
        }
        
        fmt.Println(dataMap)
    }

    If you want to parse a YAML file into a Go map but are having trouble defining the appropriate struct, there are a couple of alternatives you can use. In Go, you can read a YAML file without needing to define a struct by using the `map[string]interface{}` type. This method lets you load the YAML content into a nested map structure, bypassing the need for a specific struct definition.