Match array according to value

2019-07-08 05:02发布

问题:

I'm using the following code to parse yaml and should get output as runners object and the function buildshould change the data structure and provide output according to below struct

type Exec struct {
    NameVal string
    Executer []string
}

This is what I have tried but I'm not sure how to replace the hard-code values inside the function runner from the value I'm getting inside the yaml

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

with the data from the parsed runner

This is all what I have tried any idea how it could be done?

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:

Assign the name of runners object to the struct Exec field for name and append the command list to the []string type field with the commands of the function that matched the name as:

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
}

Working code on Playground