首页 > 解决方案 > 函数无法识别 Yaml 嵌套结构

问题描述

我有以下结构 YAML:

type YamlConfig struct {
    Items struct {
        RiskyRoles []struct {
            Name string `yaml:"name"`
            Rules []struct{
                Verbs []string `yaml:"verbs"`
                ResourceOperator string `yaml:"resourcesOperator"`
                Resources []string `yaml:"resources"`
            }
        } `yaml:"RiskyRoles"`
    } `yaml:"Items"`
}  

我有一个将 YAML 文件解析为对象的函数,然后我想将Rulesstruct 对象发送到名为的函数DoingStuff(..)

yamlFile, err := ioutil.ReadFile("actionItems.yaml")
if err != nil {
    fmt.Printf("Error reading YAML file: %s\n", err)
} else{
    var yamlConfig YamlConfig
    err = yaml.Unmarshal(yamlFile, &yamlConfig)
    if err != nil {
        fmt.Printf("Error parsing YAML file: %s\n", err)
    }

    for _, yamlRole := range yamlConfig.Items.RiskyRoles{
       DoingStuff(yamlRole.Rules)
    }
}

但在函数内部DoingStuff,结构对象Rules无法识别:

func DoingStuff(yamlRules []struct{}) {
  // Not recognize ****
  for _, rule := range yamlRules {
      fmt.Print(rule.ResourceOperator)
  }
}

我怎样才能将其转换为:

Rules []struct{
    Verbs []string `yaml:"verbs"`
    ResourceOperator string `yaml:"resourcesOperator"`
    Resources []string `yaml:"resources"`
}

我应该再次重新声明这个结构吗?还是使用接口进行转换?

编辑:

我添加了新结构并在YamlConfig结构中使用它,但解析无法解析规则:

type RulesStruct struct {
    Rules []struct{
        Verbs []string `yaml:"verbs"`
        ResourceOperator string `yaml:"resourcesOperator"`
        Resources []string `yaml:"resources"`
    }
}
type YamlConfig struct {
    Items struct {
        RiskyRoles []struct {
            Name string `yaml:"name"`
            Message string `yaml:"message"`
            Priority string `yaml:"priority"`
            Rules []RulesStruct
        } `yaml:"RiskyRoles"`
    } `yaml:"Items"`
}

标签: gostruct

解决方案


感谢@mkporiva 的帮助,我改变了这样的结构:

type RulesStruct struct {

    Verbs []string `yaml:"verbs"`
    ResourceOperator string `yaml:"resourcesOperator"`
    Resources []string `yaml:"resources"`

}

type YamlConfig struct {
    Items struct {
        RiskyRoles []struct {
            Name string `yaml:"name"`
            Message string `yaml:"message"`
            Priority string `yaml:"priority"`
            Rules []RulesStruct
        } `yaml:"RiskyRoles"`
    } `yaml:"Items"`
}  

现在它工作正常。


推荐阅读