具有动态架构的Golang和Yaml [英] Golang and yaml with dynamic schema
本文介绍了具有动态架构的Golang和Yaml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有动态架构的YAML结构,例如我可以使用以下yaml:
I have a YAML structure with dynamic schema e.g. I can have the following yaml:
array:
- name: myvar
val: 1
- name: mymap
val: [ 1, 2]
Goyaml将yaml映射到Go结构,该结构应声明确定的类型.在这里,val
是一个数字,或者是一个数组,甚至是一个映射.
Goyaml maps yaml to Go struct, which should declare definite type. Here, val
is either a signle number, or an array or even a map.
哪种方法最适合这种情况?
Which is the best solution for this situation?
推荐答案
我决定添加一个显示类型断言的答案,而不是reflect
包.您可以决定最适合您的应用程序.我个人更喜欢内置函数,而不是reflect
软件包的复杂性.
I decided to add an answer showing a type assertion instead of the reflect
package. You can decide which is best for your application. I personally prefer the builtin functions over the complexity of the reflect
package.
var data = `
array:
- name: myvar
val: 1
- name: mymap
val: [1, 2]
`
type Data struct {
Array []struct {
Name string
Val interface{}
}
}
func main() {
d := Data{}
err := yaml.Unmarshal([]byte(data), &d)
if err != nil {
log.Fatal(err)
}
for i := range d.Array {
switch val := d.Array[i].(type) {
case int:
fmt.Println(val) // is integer
case []int:
fmt.Println(val) // is []int
case []string:
fmt.Println(val) // is []string
// .... you get the idea
default:
log.Fatalf("Type unaccounted for: %+v\n", d.Array[i])
}
}
}
这篇关于具有动态架构的Golang和Yaml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文