gpt4 book ai didi

go - 在 Go 中附加到结构 slice

转载 作者:IT王子 更新时间:2023-10-29 02:26:11 26 4
gpt4 key购买 nike

我有两个结构,像这样:

// 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com