登录
首页 >  Golang >  Go问答

根据值匹配数组

来源:stackoverflow

时间:2024-04-23 23:48:35 257浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《根据值匹配数组》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

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

type exec struct {
    nameval string
    executer []string
}

这是我尝试过的,但我不知道如何替换 函数运行器内的硬编码值来自我在 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 对象的名称分配给 struct exec 字段作为名称,并将命令列表附加到 []string 类型字段,其中包含与名称匹配的函数的命令:

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 上的工作代码

终于介绍完啦!小伙伴们,这篇关于《根据值匹配数组》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>