# go get gopkg.in/yaml.v2
# vi test.yml
test.yml
first: test
secound:
a1: count1
a2:
- count2
- count3
a3:
b1: count4
# vi main.go
main.go
package main
import(
"fmt"
"io/ioutil"
"strconv"
"gopkg.in/yaml.v2"
)
func main() {
// test.Lire yml
buf, err := ioutil.ReadFile("test.yml")
if err != nil {
fmt.Print("error: Failed to read the file\n")
return
}
//Mapper le fichier lu[interface {}]interface {}Carte pour
t := make(map[interface {}]interface {})
err = yaml.Unmarshal(buf, &t)
if err != nil {
panic(err)
}
fmt.Print(t["first"]) // test
fmt.Print("\n")
// t["secound"]À(map[interface {}]interface {})Conversion de type avec
fmt.Print(t["secound"].(map[interface {}]interface {})["a1"]) //count1
fmt.Print("\n")
// len()Renvoie le nombre d'éléments dans le tableau
fmt.Print(len(t["secound"].(map[interface {}]interface {})))
fmt.Print("\n")
// []interface {}Tableau de types
fmt.Print(t["secound"].(map[interface {}]interface {})["a2"].([]interface {})[0]) // count2
fmt.Print("\n")
fmt.Print(t["secound"].(map[interface {}]interface {})["a3"].(map[interface {}]interface {})["b1"]) // count4
fmt.Print("\n")
//S'il est nommé régulièrement, vous pouvez vérifier combien il y en a
flag, i := 0, 0
for flag == 0 {
i++
switch t["secound"].(map[interface {}]interface {})["a"+strconv.Itoa(i)].(type) {
case nil:
flag = 1
}
}
fmt.Printf("a%d is not found\n", i) // a4 is not found
}
# go run main.go
test
count1
3
count2
count4
a4 is not found
Recommended Posts