Golang和YAML与动态模式

huangapple go评论92阅读模式
英文:

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])
		}
	}

}

huangapple
  • 本文由 发表于 2017年8月7日 22:44:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/45549682.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定