如何在golang中

时间:2016-12-13 06:42:19

标签: json go struct

我有以下数据结构。我需要在不使用嵌套初始化的情况下初始化它。将刷新此数据结构以便稍后输出json文件。

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

如何在不使用new或任何ptr的情况下初始化struct?因为,如果我们使用任何标准的struct初始化技术,它将给出上述错误。 如果我更改上面的数据结构并使其保持指向另一个结构的指针,它不会正确存储值。我对golang很新。任何帮助表示赞赏。提前谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用以下命令初始化结构值:

resource := struct2{}

正如@nothingmuch所指出的,如果你有一个结构指针并且需要底层值,你可以使用以下命令取消引用指针:

deref := *resource
相关问题