yaml 文件:
# items.yaml
items:
- path: aaaa
- path: bbbb
weight: "10"
- path: cccc
weight: "-5"
Go 代码:
// main.go
package main
import (
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
)
type Item struct {
Path string `yaml:"path"`
Weight string `yaml:"weight"`
}
type Items struct {
Items []Item `yaml:"items"`
}
func main() {
var items Items
yamlFile, err := ioutil.ReadFile("items.yaml")
if err != nil {
fmt.Printf("failed to read yaml file : %v\n", err)
return
}
err = yaml.Unmarshal(yamlFile, &items)
if err != nil {
fmt.Printf("failed to unmarshal : %v\n", err)
return
}
fmt.Println(items)
}
编译执行结果如下:
go build main.go
./main
{[{aaaa } {bbbb 10} {cccc -5}]}