Type

在 go 中解组 yaml 时,要求:

解码值的类型应与输出中的相应值兼容。如果一个或多个值由于类型不匹配而无法解码,解码将继续部分进行,直到 YAML 内容结束,并返回一个 *yaml.TypeError,其中包含所有缺失值的详细信息。

与此同时:

结构字段只有在导出时才会被解组(首字母大写),并且使用小写的字段名称作为默认键进行解组。

yaml

type Runners struct {


    runners string `yaml:"runners"` // fields should be exportable

        name string `yaml:”name”`

        Type: string  `yaml: ”type”` // tags name should not have space in them.

        command  [] Command 

要使结构可导出,请将结构和字段转换为大写首字母并删除 yaml 标签名称中的空格:


type Runners struct {

    Runners string `yaml:"runners"`

    Name string `yaml:"name"`

    Type string `yaml:"type"`

    Command  []Command 

}


type Command struct {

    Command string `yaml:"command"`

}

修改下面的代码以使其工作。


package main


import (

    "fmt"

    "log"


    "gopkg.in/yaml.v2"

)


var runContent = []byte(`

- runners:

  - name: function1

    type:

    - command: spawn child process

    - command: build

    - command: gulp

  - name: function1

    type:

    - command: run function 1

  - name: function3

    type:

    - command: ruby build

  - name: function4

    type:

    - command: go build

`)


type Runners []struct {

    Runners []struct {

        Type []struct {

            Command string `yaml:"command"`

        } `yaml:"type"`

        Name string `yaml:"name"`

    } `yaml:"runners"`

}


func main() {


    runners := Runners{}

    // parse mta yaml

    err := yaml.Unmarshal(runContent, &runners)

    if err != nil {

        log.Fatalf("Error : %v", err)

    }

    fmt.Println(runners)

}