【发布时间】:2015-03-30 18:29:05
【问题描述】:
我是 Golang 的新手,请原谅我的新手。
我目前正在使用 yaml.v2 包 (https://github.com/go-yaml/yaml) 将 YAML 数据解组到结构中。
考虑以下示例代码:
package main
import (
"fmt"
"gopkg.in/yaml.v2"
"log"
)
type Container struct {
First string
Second struct {
Nested1 string
Nested2 string
Nested3 string
Nested4 int
}
}
var data = `
first: first value
second:
nested1: GET
nested2: /bin/bash
nested3: /usr/local/bin/customscript
nested4: 8080
first: second value
second:
nested1: POST
nested2: /bin/ksh
nested3: /usr/local/bin/customscript2
nested4: 8081
`
func main() {
container := Container{}
err := yaml.Unmarshal([]byte(data), &container)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("---values found:\n%+v\n\n", container)
}
结果:
---values found: {First:second value Second:{Nested1:POST Nested2:/bin/ksh Nested3:/usr/local/bin/customscript2 Nested4:8081}}
正如预期的那样,unmarshal 函数找到了 YAML 数据的一次出现。
我想做的是编写一个简单的 while/each/for 循环,该循环遍历数据变量并将所有出现的事件编组到单独的 Container 结构中。我怎样才能做到这一点?
【问题讨论】: