gpt4 book ai didi

Go YAML 解析器静默失败

转载 作者:IT王子 更新时间:2023-10-29 01:55:10 27 4
gpt4 key购买 nike

我正在尝试使用 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.

请注意此处的重要位:“如果需要,则初始化结构中的指针”,以及“如果无法解码值,则返回 yaml.TypeError”。

现在:

主要包

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]

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

 OK
TypeA.D:
I have 0 TypeB

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

最佳答案

你的结构标签中有空格,所以它们被忽略了:

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"`
}

关于Go YAML 解析器静默失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34299049/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com