英文:
Golang and yaml with dynamic schema
问题
我有一个具有动态模式的YAML结构,例如我可以有以下的yaml结构:
array:
- name: myvar
val: 1
- name: mymap
val: [ 1, 2]
Goyaml将yaml映射到Go结构体,该结构体应声明明确的类型。在这里,val
可以是一个单独的数字,也可以是一个数组,甚至是一个映射。
对于这种情况,哪种解决方案是最好的?
英文:
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 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?
答案1
得分: 3
我决定添加一个显示类型断言而不是使用reflect
包的答案。你可以决定哪个对你的应用程序更好。我个人更喜欢内置函数,而不是reflect
包的复杂性。
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].Val.(type) {
case int:
fmt.Println(val) // 是整数
case []int:
fmt.Println(val) // 是 []int
case []string:
fmt.Println(val) // 是 []string
// ....你明白了
default:
log.Fatalf("未处理的类型: %+v\n", d.Array[i])
}
}
}
英文:
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])
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论