【问题标题】:Appending to struct slice in Go在 Go 中附加到结构切片
【发布时间】:2018-12-05 06:49:47
【问题描述】:

我有两个结构,像这样:

// init a struct for a single item
type Cluster struct {
  Name string
  Path string
}

// init a grouping struct
type Clusters struct {
  Cluster []Cluster
}

我想要做的是将新项目附加到 clusters 结构中。所以我写了一个方法,像这样:

func (c *Clusters) AddItem(item Cluster) []Cluster {
  c.Cluster = append(c.Cluster, item)
  return c.Cluster
}

我的应用程序的工作方式是遍历一些目录,然后附加最终目录的名称及其路径。我有一个函数,叫做:

func getClusters(searchDir string) Clusters {

  fileList := make([]string, 0)
  //clusterName := make([]string, 0)
  //pathName := make([]string, 0)

  e := filepath.Walk(searchDir, func(path string, f os.FileInfo, err error) error {
    fileList = append(fileList, path)
    return err
  })

  if e != nil {
    log.Fatal("Error building cluster list: ", e)
  }

  for _, file := range fileList {

    splitFile := strings.Split(file, "/")
    // get the filename
    fileName := splitFile[len(splitFile)-1]

    if fileName == "cluster.jsonnet" {
      entry := Cluster{Name: splitFile[len(splitFile)-2], Path: strings.Join(splitFile[:len(splitFile)-1], "/")}
      c.AddItem(entry)

    }
  }
  Cluster := []Cluster{}
  c := Clusters{Cluster}

  return c

}

这里的问题是我不知道正确的方法。

目前,我得到:

cmd/directories.go:41:4: 未定义:c

所以我试着移动这个:

Cluster := []Cluster{}
c := Clusters{Cluster}

在 for 循环上方 - range。我得到的错误是:

cmd/directories.go:43:20: 集群不是类型

我在这里做错了什么?

【问题讨论】:

    标签: go struct slice


    【解决方案1】:

    错误出现在您在集群方法接收器上调用AddItem 函数的循环中,该函数未在getClusters 函数中定义。在for循环之前定义Cluster结构,然后调用函数c.AddItem,定义如下:

    func getClusters(searchDir string) Clusters {
    
        fileList := make([]string, 0)
        fileList = append(fileList, "f1", "f2", "f3")
    
        ClusterData := []Cluster{}
        c := Clusters{Cluster: ClusterData} // change the struct name passed to Clusters struct
    
        for _, file := range fileList {
    
            entry := Cluster{Name: "name" + file, Path: "path" + file}
            c.AddItem(entry)
        }
        return c
    
    }
    

    您已将相同的结构名称定义为 Clusters 结构,这就是错误的原因

    cmd/directories.go:43:20: 集群不是类型

    Go playground上结帐工作代码

    在Golang中Composite literal定义为:

    复合文字为结构、数组、切片和映射构造值,并在每次评估它们时创建一个新值。他们 由字面量的类型后跟大括号绑定列表组成 元素。每个元素可以可选地在一个对应的前面 键。

    还可以查看上面链接中定义的结构文字部分,以获取更多描述。

    【讨论】:

    • 我一看到你的回答,就知道我做了什么!谢谢,关键是更改结构名称。也许我需要更多的咖啡,谢谢!
    【解决方案2】:

    你需要定义c之前进入你使用它的循环。

    Cluster is not a type 错误是由于使用了与类型和变量相同的Cluster 名称,请尝试使用不同的变量名称。

    clusterArr := []Cluster{}
    c := Clusters{clusterArr}
    
    for _, file := range fileList {
       ....
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-05
      • 2016-12-08
      • 1970-01-01
      • 2016-06-04
      • 2016-12-24
      • 2016-07-22
      • 2017-07-27
      • 2019-04-12
      相关资源
      最近更新 更多