2016-03-09 113 views
1

所以我一直在試圖填充我創建的這個怪物的結構,但沒有成功。如何填充嵌套的golang結構,其中包含一個結構數組

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" 
            } 
         ] 
      } 
   ] 
} 

有大約填充嵌套結構回答問題,但我還沒有找到一個包含結構的數組。我知道這可能很簡單,但我無法弄清楚。謝謝。

回答

2

您可能需要將這些內部結構定義爲類型。這個作品:

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

我只寫了1章,但你明白了。

+0

謝謝!這是我遇到的部分:Pages:[] Page {{Description:「def」,PageNumber:3,Source:「xyz」,},{Description:「qrs」,PageNumber:5,Source:「xxx 「,} –