根据值匹配数组

时间:2018-08-21 12:26:43

标签: go struct yaml slice

我正在使用以下代码来解析yaml,并且应将输出作为runners对象,而函数build应该更改数据结构并根据以下结构提供输出

type Exec struct {
    NameVal string
    Executer []string
}

这是我尝试过的方法,但是我不确定如何替换 我从yaml里面获取的值,在函数运行器中获取硬代码值

return []Exec{
    {"#mytest",
        []string{"spawn child process", "build", "gulp"}},
}

使用parsed runner

中的数据

这就是我尝试过的所有想法,该怎么做?

package main

import (
    "log"

    "gopkg.in/yaml.v2"
)

var runContent = []byte(`
api_ver: 1
runners:
  - name: function1
    data: mytest
    type:
    - command: spawn child process
    - command: build
    - command: gulp
  - name: function2
    data: mytest2
    type:
    - command: webpack
  - name: function3
    data: mytest3
    type:
    - command: ruby build
  - name: function4
    type:
  - command: go build
`)

type Result struct {
    Version string    `yaml:"api_ver"`
    Runners []Runners `yaml:"runners"`
}

type Runners struct {
    Name string    `yaml:"name"`
    Type []Command `yaml:"type"`
}

type Command struct {
    Command string `yaml:"command"`
}

func main() {

    var runners Result
    err := yaml.Unmarshal(runContent, &runners)
    if err != nil {
        log.Fatalf("Error : %v", err)
    }

    //Here Im calling to the function with the parsed structured data  which need to return the list of Exec
    build("function1", runners)

}

type Exec struct {
    NameVal  string
    Executer []string
}

func build(name string, runners Result) []Exec {

    for _, runner := range runners.Runners {

        if name == runner.Name {
            return []Exec{
                // this just for example, nameVal and Command
                {"# mytest",
                    []string{"spawn child process", "build", "gulp"}},
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

将runners对象的名称分配给结构Exec字段以获取名称,并使用与名称匹配的函数命令将命令列表附加到[]string type字段:

func build(name string, runners Result) []Exec {
    exec := make([]Exec, len(runners.Runners))
    for i, runner := range runners.Runners {

        if name == runner.Name {
            exec[i].NameVal = runner.Name
            for _, cmd := range runner.Type {
                exec[i].Executer = append(exec[i].Executer, cmd.Command)
            }
            fmt.Printf("%+v", exec)
            return exec
        }
    }
    return exec
}

Playground上工作的代码