2016-12-13 44 views
-1

我有以下數據結構。我需要初始化它而不使用嵌套的初始化。這個數據結構將被刷新以後輸出一個json文件。如何在golang中初始化以下結構的結構

type GeneratePlan struct{ 
    Mode string `json:"mode"` 
    Name string `json:"name"` 
    Schema string `json:"schema"` 
    Version string `json:"version"` 
    Attack_plans []struct1 `json:"attack-plans"` 

} 

type struct1 struct { 
    Attack_plan Attack_plan `json:"attack-plan"` 
} 


type Attack_plan struct{ 
    Attack_resouces []struct2 `json:"attack-resources"` 
} 

type struct2 struct { 
    Attack_resource Attack_resource `json:"attack-resource"` 
} 

問題是,當我嘗試類型struct2到Attack_resources []切片變量追加,它給出了錯誤的

cannot use struct2 (type *structs.Struct2) as type structs.Struct2 in append 

我們如何初始化結構,而無需使用新的或任何PTR ?因爲,如果我們使用任何標準的結構初始化技術,它會給出上述錯誤。 如果我改變了上面的數據結構並且讓它保存了一個指向另一個結構體的指針,它就不會正確地存儲這些值。我對golang很新。任何幫助表示讚賞。提前致謝!

+1

請確保將來發布實際失敗的代碼。該錯誤消息也與您的代碼示例不匹配。 你的問題是你正在將一個指針值附加到一個結構片。將切片定義更改爲'[] * Struct2',或者像'x.Attack_resources = append(x.Attack_resources,* struct2)'中那樣取消引用指針。 請注意,snake_case通常不會受到鼓勵。 – nothingmuch

回答

0

可以使用初始化一個struct值:

resource := struct2{} 

由於@nothingmuch指出的那樣,如果你有一個結構的指針和所需要的潛在價值,你可以取消引用指針使用:

deref := *resource 
+0

該解決方案給了我一個提示繼續。萬分感謝!!! – Aishwarya