go - 根据值匹配数组

标签 go struct yaml slice

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

type Exec struct {
    NameVal string
    Executer []string
}

这是我尝试过的方法,但我不确定如何替换 函数运行程序中的硬编码值 来 self 在 yaml 中获取的值

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

使用来自已解析的运行器的数据

这就是我尝试过的所有方法,不知道如何完成?

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"}},
            }
        }
    }
}

最佳答案

将 runners 对象的名称分配给 name 的 struct 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 上的工作代码

关于go - 根据值匹配数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51948670/

相关文章:

c - 如何在c中正确分配和打印结构指针?

c - 结构中的结构数组 (C)

c - 读/写结构到套接字

bash - 无法在 GitLab CI YAML 中打印包含双引号的字符串

go - 如何在 travis-ci 上使用远程包 |走

go - 模式匹配后如何查找文本

amazon-web-services - Cloudformation 如何在 Sub 内的 ImportValue 内进行 Sub ?

azure-devops - 部署作业的检查(批准)阻碍了整个阶段

go - 如何访问 golang 中的嵌套映射数据?

Go: *Var 是 Var 的 "subclass"吗?