将YAML解组到Go中包含意外字段的结构

将YAML解组到Go中包含意外字段的结构,go,struct,yaml,unmarshalling,Go,Struct,Yaml,Unmarshalling,我使用github.com/go-yaml/yaml尝试对具有未报告字段的结构进行解组时遇到问题。结构看起来像: type Example struct { ExportedField string `yaml:"exported-field"` OneMoreExported string `yaml:"one-more-exported"` unexportedField map[st

我使用
github.com/go-yaml/yaml
尝试对具有未报告字段的结构进行解组时遇到问题。结构看起来像:

type Example struct {
    ExportedField   string                     `yaml:"exported-field"`
    OneMoreExported string                     `yaml:"one-more-exported"`
    unexportedField map[string]*AnotherExample `yaml:"unexported-field"`
}

type AnotherExample struct {
    Name string `yaml:"name"`
}
我想解开这样的YAML

exported-field: lorem ipsum
one-more-exported: dolor set
unexported-field:
  something:
    name: anything
我尝试的是自定义解组器:

func (example *Example) UnmarshalYAML(unmarshal func(interface{}) error) error {
    type Alias Example
    tmp := struct {
        UnexportedField map[string]*AnotherExample `yaml:"unexported-field"`
        *Alias
    }{
        Alias: (*Alias)(example),
    }
    if err := unmarshal(&tmp); err != nil {
        return err
    }
    if tmp.UnexportedField != nil {
        example.unexportedField = tmp.UnexportedField
    }
    example.CopyJobNonNil(Example(*tmp.Alias)) // Copies all the non-nil fields from the passed Example instance

    return nil
}
调用
unmarshal()后
tmp
不包含任何字段,但未报告字段-其他字段似乎被忽略


Go Playerd上重现的问题(尽管它由于依赖性而无法工作):

因为大多数Go解组包(包括
编码/*
包)使用
反射
包获取结构字段,而
反射
无法访问未报告的结构字段,解组器无法解析为未报告的字段

尽管如此,仍然有办法做到这一点。您可以使用公共字段将YAML解组为未报告的类型,然后可以将其嵌入到导出的类型中。同一个包中的getter和setter只能使用嵌入式结构

例如:

// Define the types...

type innerData struct {
    ExportedField string
    unexportedField string
}

type Data struct {
    innerData
}


// and then...

d := Data{}
DoSomeUnmarshalling(yamlbytes, &d.innerData)


// and then you can use getters/setters/whatever on `Data`

func (d *Data) GetUnexported() string {
    return d.innerData.unexportedField;
}
(警告:完全未经测试)

请参阅以供参考