2016-12-27 36 views
3

我想在Go中编写一个函数,它需要一个JSON与一个目录的URL并执行BFS来查找该目录中的文件。当我找到一个作为目录的JSON时,代码会生成一个URL并且应该排入该URL。当我尝试在循环中创建append()中的结构时,出现错误。Golang不能用作类型结构数组或切片文字

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 

回答

3

ContentResp类型是,不是结构,但你把它当作一个结构,当你使用一个composite literal试图建立它的值:

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, ...) 
} 

上面的代码覆盖一个切片,并在其内部尝试将元素附加到切片。与此相关的2个问题:append()返回必须存储的结果(它甚至可能必须分配一个新的,更大的支持数组并复制现有元素,在这种情况下,结果片将指向完全不同的数组,并且旧的应该被抛弃)。所以它应该像这样使用:

contentResps = append(contentResps, ...) 

第二:你不应该改变你正在覆盖的切片。 for ... range评估范围表达式一次(最多),因此您更改它(向其添加元素)将不会影响迭代器代码(它不会看到切片标头更改)。

如果你有这样的情况,你需要完成“任务”,但是在执行期间可能会出现新的任务(递归地完成),通道是一个更好的解决方案。看到这个答案,以获得渠道的感觉:What are golang channels used for?

相关问题