使用地图阅读Golang YAML

使用地图阅读Golang YAML,go,yaml,Go,Yaml,这是我的YAML文件 description: fruits are delicious fruits: apple: - red - sweet lemon: - yellow - sour 我可以用gopkg.in/yaml.v1软件包来阅读这篇文章的更平淡的版本,但是我一直在试图弄清楚当这个yaml文件有一张地图的时候如何阅读它 package main import ( "fmt" "gopkg.in/yaml.v1" "io/io

这是我的YAML文件

description: fruits are delicious
fruits:
  apple:
    - red
    - sweet
  lemon:
    - yellow
    - sour
我可以用
gopkg.in/yaml.v1
软件包来阅读这篇文章的更平淡的版本,但是我一直在试图弄清楚当这个yaml文件有一张地图的时候如何阅读它

package main

import (
  "fmt"
  "gopkg.in/yaml.v1"
  "io/ioutil"
  "path/filepath"
)

type Config struct {
  Description string
  Fruits []Fruit
}

type Fruit struct {
  Name string
  Properties []string
}

func main() {
  filename, _ := filepath.Abs("./file.yml")
  yamlFile, err := ioutil.ReadFile(filename)

  if err != nil {
    panic(err)
  }

  var config Config

  err = yaml.Unmarshal(yamlFile, &config)
  if err != nil {
    panic(err)
  }

  fmt.Printf("Value: %#v\n", config.Description)
  fmt.Printf("Value: %#v\n", config.Fruits)
}

它无法取出嵌套的水果。它似乎是空的<代码>值:[]main.Fruit(nil)

使用字符串切片映射来表示水果属性:

type Config struct {
  Description string
  Fruits map[string][]string
}
使用打印未经授权的配置

fmt.Printf("%#v\n", config)
生成以下输出(不包括为可读性而添加的空白):

main.Config{Description:"fruits are delicious", 
     Fruits:map[string][]string{
          "lemon":[]string{"yellow", "sour"}, 
          "apple":[]string{"red", "sweet"}}}