Go 函数无法识别Yaml嵌套结构
我有以下结构YAML:Go 函数无法识别Yaml嵌套结构,go,struct,Go,Struct,我有以下结构YAML: type YamlConfig struct { Items struct { RiskyRoles []struct { Name string `yaml:"name"` Rules []struct{ Verbs []string `yaml:"verbs"` ResourceOperator string `yaml:"resou
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文件解析为对象的函数,然后我想将Rules struct对象发送给名为DoingStuff.的函数:
但在函数DoingStuff中,无法识别结构对象规则:
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"`
}
感谢@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"`
}
现在它可以正常工作。声明一个命名结构,并在yaml配置和函数参数中使用它。请注意,无法识别struct对象规则是因为类型[]struct{}和规则字段的类型显然不同。我尝试了它,但它没有解析规则,可能是我没有正确执行?看到我的编辑。很难说为什么没有看到yaml文件。但是请注意,您的Rules[]RulesStruct字段缺少yaml标记,并且结构与以前匿名版本的Rules字段不同。好的,我成功地做到了,发现了我的问题,谢谢!我会公布答案
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"`
}