我有以下数据结构。我需要在不使用嵌套初始化的情况下对其进行初始化。稍后将刷新此数据结构以输出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的情况下初始化结构?因为,如果我们使用任何标准的结构初始化技术,都会产生上述错误。如果更改上面的数据结构,并使其保留指向另一个结构的指针,则它将无法正确存储值。我刚接触golang。任何帮助表示赞赏。提前致谢!
您可以使用以下方法初始化结构值:
resource := struct2{}
正如@nothingmuch所指出的那样,如果您具有struct指针并且需要基础值,则可以使用以下方式取消引用该指针:
deref := *resource
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句