go - 函数无法识别 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 文件解析为对象的函数,然后我想将Rules
struct 对象发送到名为的函数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"`
}
解决方案
感谢@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"`
}
现在它工作正常。
推荐阅读
- python - 如何让多个小部件按钮在 Jupyter Notebook 中执行不同的操作?
- javascript - 如何在javascript中拦截“in”运算符?
- java - 错误:类 LineData 中的构造函数 LineData 不能应用于给定类型;
- java - JNI 错误 - 使用 CallVoidMethod 时无法调用 [method]
- c# - 如何从 Blazor 页面访问 env.IsDevelopment()?
- ruby-on-rails - 尝试在heroku上部署rails应用程序时出错
- d - 如何在 Visual Studio 中运行 D 代码程序?Ubuntu 18.04
- php - Laravel 6 中打包 tymondesigns/jwt-auth 安装问题
- python-3.x - Python中是否有一个函数用于计算从带有中断的“for”循环创建的输出数量?
- typescript - 如何根据另一个参数确定一个参数是否必要?