将结构从字符串数组更改为深度数组

问题描述:

I’ve the following structure which I created manually the values like app service runner etc

func Cmr(mPath string) [][]string {
    cav := [][]string{
        {mPath, "app", "app2"},
        {mPath, "service"},
        {mPath, "runner1", "runner2", "runner3"},
    }
    return cav
}

Now I need from this input to create this struct, I mean to return the same structure ‘cav`

Now I’ve other function which returns array of string name cmdList each line have a space delimiter between values like app app2 appN

0 = app app2
1 = service
2 = runner1 runner2 runner3 

How can I take the above array of string and put it as parameter to the function Cmr And remove the hard-coded value and get them from the cmdList instead of hard-coded them...

Like

func Cmr(mPath string,cmdList []string) [][]string {
    cav := [][]string{
        {mPath, cmdList[0], "app2"},
        {mPath, "service"},
        {mPath, "runner1", "runner2", "runner3"},
    }
    return cav
}

update at the end it should be something like this except the I dont know how to split the entry of the cmdList with the space delimiter

func Cmr(mPath string, cmdList []string) [][]string {
    cav := [][]string{}

    cav = append(cav, append([]string{mPath}, cmdList[0]))
    cav = append(cav, append([]string{mPath}, cmdList[1]))
    cav = append(cav, append([]string{mPath}, cmdList[2]))

    return cav
}

This will create something like (since Im not handling the space delimiter)

   cav := [][]string{
        {mPath, "app app2"},
        {mPath, "service"},
        {mPath, "runner1 runner2 runner3"},
    }

But I need

  cav := [][]string{
        {mPath, "app", "app2"},
        {mPath, "service"},
        {mPath, "runner1", "runner2", "runner3"},
    }

I imagine you're looking for something like:

cav = append(cav, strArray)

where strArray is the array of strings you've received from cmdList()

EDIT: this ended up being what they were looking for: https://play.golang.org/p/ZFFhRRu43Em

Basically from what I see it seems you should be getting those string slices by argument, and append them to your [][]string.

Here is a complete example, where they are passed to the function:

package main

import "fmt"

func Cmr(mPath string, appList, serviceList, runnerList []string) [][]string {
    cav := [][]string{}
    cav = append(cav, append([]string{mPath}, appList...))
    cav = append(cav, append([]string{mPath}, serviceList...))
    cav = append(cav, append([]string{mPath}, runnerList...))

    return cav
}

func main() {
    cmr := Cmr(
        "mpathTestValue",
        []string{"app1", "app2"},
        []string{"service1", "service2"},
        []string{"runner1", "runner2", "runner3"},
    )

    for _, values := range cmr {
        fmt.Println(values)
    }
}

Gives the output

[mpathTestValue app1 app2]
[mpathTestValue service1 service2]
[mpathTestValue runner1 runner2 runner3]

You can try playing with it yourself here