golang附加到2d切片

问题描述 投票:0回答:1

我正在尝试创建切片切片。

在所有示例中,内部切片都是基于整数的。

我正在尝试创建一个字符串切片的切片。

示例:

[
[Name1,State1,Tags.Owner1]
[Name2,State2,Tags.Owner2]
[Name3,State3,Tags.Owner3]
]

我正在尝试通过这种方式:

outerList :=  [][]string{}

i := 0
  for _,c := range clusters {
    input := &eks.DescribeClusterInput{
      Name: aws.String(c),
    }

   resp,err := svc.DescribeCluster(input)
    if err != nil {
        errorOut(`clusterData function: `+err.Error())
    }
    record := resp.Cluster
    data,_ := json.Marshal(record)
    error := json.Unmarshal(data, &cluster)
    if error != nil {errorOut(error.Error())}
    innerList := [...]string{cluster.Name,cluster.Tags["Vsad"],cluster.Status}
    outerList[string(i)] = innerList
  }

我收到以下错误:

non-integer slice index string(i) 
cannot use innerList (type [3]string) as type []string in assignment 

我知道在Python中我可以轻松做到:

outerList = list()

for c in cluster:
  a = [c.Name,c.State,c.Tags.Owner]
  outerList.append(a)
amazon-web-services go slice
1个回答
2
投票

您可以使用append。格式如下:

// make room for clusters
outerList := make([][]string, len(clusters))

// iterate and fill cluster data
for i, c := range clusters {
  // some processing where cluster variable is setupped

  // add new inner slice
  outerList[i] = append(outerList[i], cluster.Name, cluster.Tags["Vsad"], cluster.Status)
}
© www.soinside.com 2019 - 2024. All rights reserved.