Go YAML 解析器静默失败

Go YAML parser failing silently

我正在尝试使用 gopkg.in/yaml.v2 进行简单的 YAML 解析。

来自the documentation

Maps and pointers (to a struct, string, int, etc) are accepted as out values. If an internal pointer within a struct is not initialized, the yaml package will initialize it if necessary for unmarshalling the provided data. The out parameter must not be nil.

The type of the decoded values should be compatible with the respective values in out. If one or more values cannot be decoded due to a type mismatches, decoding continues partially until the end of the YAML content, and a *yaml.TypeError is returned with details for all missed values.

请注意此处的重要位:"pointer within struct initialized if nec'y" 和 "yaml.TypeError returned if a value can't be decoded"。

现在:

主要包

import (
    "fmt"
    "gopkg.in/yaml.v2"
)

type YamlTypeA struct {
    D string    `yaml: "d"`
    E string    `yaml: "e"`
}

type YamlTypeB struct {
    F string    `yaml: "f"`
}

type YamlTypeC struct {
    TypeA   *YamlTypeA      `yaml: "a"`
    TypeB   []YamlTypeB `yaml: "b"`
}

func main() {
    var yamlObj YamlTypeC

    text := []byte(`
---
a:  
   d: foo 
   e: bar
b: [{f: "fails"},
    {f: "completely"}]
`)

    err := yaml.Unmarshal(text,&yamlObj)
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    fmt.Println("OK")
    fmt.Printf("TypeA.D: %s\n", yamlObj.TypeA.D)
    fmt.Printf("I have %d TypeB\n", len(yamlObj.TypeB))
}

产量

 OK
 panic: runtime error: invalid memory address or nil pointer dereference
 [signal 0xb code=0x1 addr=0x0 pc=0x4014b3]

这似乎违反了共同在文档中做出的承诺。如果我使嵌套的 YamlTypeA 立即而不是指针,结果是输出值没有被触及,仍然没有错误:

 OK
 TypeA.D: 
 I have 0 TypeB

这里有什么?它只是损坏/记录不完整吗?如何获取嵌套的结构值以从 YAML 中解析出来? (使用地图的地图很麻烦,这里根本不是解决方案。)

您的结构标签中有空格,因此它们被忽略了:

type YamlTypeA struct {
    D string `yaml:"d"`
    E string `yaml:"e"`
}

type YamlTypeB struct {
    F string `yaml:"f"`
}

type YamlTypeC struct {
    TypeA *YamlTypeA  `yaml:"a"`
    TypeB []YamlTypeB `yaml:"b"`
}