我有以下代碼,我只想測試我是否正確編組了我的 JSON:package mainimport ( "encoding/json" "fmt") type TestFile struct { Download_Seconds int `json:"download_seconds"` Name string `json:"name"` } type TestFileList struct { File *TestFile `json:"file"` }type TestSpec struct { Files []*TestFileList `json:"files"` } func main() { r := new(TestSpec) b, _ := json.Marshal(r) fmt.Println(string(b)) MyJSON := &TestSpec{Files: []&TestFileList{File: &TestFile{Download_Seconds: 600, Name: "filename1"}, File: &TestFile{Download_Seconds: 1200, Name: "filename2"}}} b1, _ := json.Marshal(MyJSON) fmt.Println(string(b1))} 我收到此錯誤:.\go_json_eg2.go:28:32: syntax error: unexpected &, expecting type.Line no: 28因為我的代碼是MyJSON := &TestSpec{Files: []&TestFileList{File: &TestFile{Download_Seconds: 600, Name: "filename1"}, File: &TestFile{Download_Seconds: 1200, Name: "filename2"}}}Go 封送處理相當新。我想我做錯了[]&TestFileList{File: &TestFile{Download_Seconds: 600, Name: "filename1"}, File: &TestFile{Download_Seconds: 1200, Name: "filename2"}}。如何解決這個問題?
1 回答

慕運維8079593
TA貢獻1876條經驗 獲得超5個贊
&TestSpec{
Files: []*TestFileList{
{File: &TestFile{Download_Seconds: 600, Name: "filename1"}},
{File: &TestFile{Download_Seconds: 1200, Name: "filename2"}},
},
}
https://go.dev/play/p/I30Mm0CxrUT
請注意,除了 Zombo 在評論中指出的錯誤之外,您還遺漏了分隔切片中各個元素的花括號,即您有{File: ..., File: ...},但它應該是{{File: ...}, {File: ...}}。
您可以在此處閱讀有關復合文字 的更多信息。
- 1 回答
- 0 關注
- 150 瀏覽
添加回答
舉報
0/150
提交
取消