如何填充嵌套的golang结构,其中包含一个结构数组

时间:2016-03-09 03:17:41

标签: go

所以我一直试图填充我创建的结构的怪物,但没有成功。

type Initial_Load struct {
    Chapters []struct {
        Name    string `Chapter Name`
        PageNum int    `Number of Page"`
        Pages   []struct {
            Description string `Page Description`
            PageNumber  int    `Page Number`
            Source      string `Page Source`
        }
    }
    NumChapters int `Total number of chapters`
}

这是该结构建模的JSON

{
   "Num_Chapters": 2,
   "Chapters": [
      {
         "Name": "Pilot",
         "Page_Num": 2,
         "Pages": [
            {
               "Page_Number": 1,
               "Source": "local.com",
               "Description": "First Page"
            },
            {
               "Page_Number": 2,
               "Source": "local.com",
               "Description": "Second Page"
            }
         ]
      },
      {
         "Name": "Chapter2",
         "Page_Num": 2,
         "Pages": [
            {
               "Page_Number": 1,
               "Source": "local.com",
               "Description": "First Page"
            },
            {
               "Page_Number": 2,
               "Source": "local.com",
               "Description": "Second Page"
            }
         ]
      },
      {
         "Name": "Chapter3",
         "Page_Num": 2,
         "Pages": [
            {
               "Page_Number": 1,
               "Source": "local.com",
               "Description": "First Page"
            },
            {
               "Page_Number": 2,
               "Source": "local.com",
               "Description": "Second Page"
            }
         ]
      }
   ]
}

有关填充嵌套结构的问题,但我没有找到包含结构数组的问题。我知道这可能很简单,但我无法弄清楚。感谢。

1 个答案:

答案 0 :(得分:3)

您可能需要将这些内部结构定义为类型。这有效:

type Page struct {
    Description string
    PageNumber  int
    Source      string
}

type Chapter struct {
    Name    string
    PageNum int
    Pages   []Page
}

type Initial_Load struct {
    Chapters    []Chapter
    NumChapters int
}

var x Initial_Load = Initial_Load{
    Chapters: []Chapter{
        {
            Name:    "abc",
            PageNum: 3,
            Pages: []Page{
                {
                    Description: "def",
                    PageNumber:  3,
                    Source:      "xyz",
                },
                {
                    Description: "qrs",
                    PageNumber:  5,
                    Source:      "xxx",
                },
            },
        },
    },
    NumChapters: 1,
}

我只写了一章,但你明白了。