具有动态架构的Golang和Yaml

编程入门 行业动态 更新时间:2024-10-07 20:28:15
本文介绍了具有动态架构的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

本文发布于:2023-11-25 21:02:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631333.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:架构   动态   Yaml   Golang

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!