为了账号安全,请及时绑定邮箱和手机立即绑定

Go JSON 编组中的指针数组

Go JSON 编组中的指针数组

Go
潇湘沐 2022-11-23 19:14:13
我有以下代码,我只想测试我是否正确编组了我的 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: ...}}。


您可以在此处阅读有关复合文字 的更多信息。


查看完整回答
反对 回复 2022-11-23
  • 1 回答
  • 0 关注
  • 91 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信