Golang无法将结构体数组或切片字面量用作类型

6

我想在Go中编写一个函数,该函数接收一个JSON,其中包含目录的URL,并执行BFS以查找该目录中的文件。当我找到一个JSON是目录时,代码会创建一个URL并将其加入队列。但是当我尝试在循环中使用append()创建结构体时,出现错误。

type ContentResp []struct {
    Name string `json:"name"`
    ContentType string `json:"type"`
    DownloadURL string `json:"download_url"`
}
...

var contentResp ContentResp
search(contentQuery, &contentResp)

for _, cont := range contentResp {
        append(contentResp, ContentResp{Name:cont.Name, ContentType:"dir", DownloadURL:cont.contentDir.String()})
}

./bfs.go:129: undefined: Name
./bfs.go:129: cannot use cont.Name (type string) as type struct { Name string "json:\"name\""; ContentType string "json:\"type\""; DownloadURL string "json:\"download_url\"" } in array or slice literal
./bfs.go:129: undefined: ContentType
./bfs.go:129: cannot use "dir" (type string) as type struct { Name string "json:\"name\""; ContentType string "json:\"type\""; DownloadURL string "json:\"download_url\"" } in array or slice literal
./bfs.go:129: undefined: DownloadURL
./bfs.go:129: cannot use cont.contentDir.String() (type string) as type struct { Name string "json:\"name\""; ContentType string "json:\"type\""; DownloadURL string "json:\"download_url\"" } in array or slice literal  
1个回答

7

您的ContentResp类型是一个切片,而不是一个结构体,但是当您使用组合字面值尝试创建它的值时,您却将其视为结构体:

type ContentResp []struct {
    // ...
}

更准确地说,它是一个匿名结构体类���的一部分。创建匿名结构体类型的值很麻烦,因此您应该创建(命名)仅为 struct 的类型,并使用该类型的切片,例如:

type ContentResp struct {
    Name        string `json:"name"`
    ContentType string `json:"type"`
    DownloadURL string `json:"download_url"`
}

var contentResps []ContentResp

进一步的问题:

让我们来看看这个循环:

for _, cont := range contentResp {
    append(contentResp, ...)
}

以上代码对切片进行了遍历,然后尝试向其中添加元素。这里有两个问题:append()会返回一个结果,必须将其存储起来(它甚至可能需要分配一个新的、更大的后备数组,并复制现有元素,在这种情况下,结果切片将指向一个完全不同的数组,旧数组应该被弃用)。因此应该像这样使用:

    contentResps = append(contentResps, ...)

第二点:你不应该改变你正在遍历的切片。 for ... range 只会对范围表达式进行一次求值(最多一次),因此你对它进行更改(添加元素)将不会影响迭代器代码(它不会看到切片头的更改)。

如果你有这样的情况,有“任务”需要完成,但在执行过程中可能会出现新的任务(要递归完成),那么通道是一个更好的解决方案。请参考这个答案,了解通道的使用感受:什么是 Golang 通道用于?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接