go - 在 Go 中附加到结构 slice

标签 go struct slice

我有两个结构,像这样:

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

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

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

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: undefined: c

所以我试着移动这个:

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

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

cmd/directories.go:43:20: Cluster is not a type

我在这里做错了什么?

最佳答案

错误出现在您在 Cluster 方法接收器上调用 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: Cluster is not a type

Go playground 上检查工作代码

在 Golang 中 Composite literal定义为:

Composite literals construct values for structs, arrays, slices, and maps and create a new value each time they are evaluated. They consist of the type of the literal followed by a brace-bound list of elements. Each element may optionally be preceded by a corresponding key.

另请查看上面链接中为 Compositeliterals 定义的 struct literals 部分,以获得更多描述。

关于go - 在 Go 中附加到结构 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51044741/

相关文章:

go - 在赋值中使用文字作为类型

docker - 无法从在Docker中运行的Go服务器连接到Elasticsearch

angular - 使用 go 提供 Angular dist 文件夹

C++:使用堆栈验证括号是否平衡(逻辑错误)

python - 在Python中,有什么理由比字符串切片更喜欢startswith吗?

google-app-engine - 如何在 Go App Engine Urlfetch 包中使用 Cookie

c - 结构指针数组的问题

c - C 结构体中的 Sizeof 指针

arrays - String to Float64 : multiple-value strconv. 单值上下文中的 ParseFloat()

python - 向后或向前读相同的单词