簡體   English   中英

Golang不能用作類型struct數組或slice文字

[英]Golang cannot use as type struct array or slice literal

我正在嘗試在Go中編寫一個函數,該函數采用帶有目錄URL的JSON並執行BFS在該目錄中查找文件。 當我找到一個作為目錄的JSON時,代碼將生成一個URL,並應將該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  

您的ContentResp類型是slice ,而不是結構,但是當您使用復合文字嘗試為其創建值時,會將其視為結構:

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 一次 (最多)計算一次范圍表達式,因此,對其進行更改(向其中添加元素)將對迭代器代碼無效(它將不會看到slice頭更改)。

如果您有“任務”要完成的情況,但是在執行過程中可能會出現新的任務(遞歸地完成),那么通道是一個更好的解決方案。 看到以下答案可以了解渠道: golang渠道有什么用途?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM