dongxie3681 2016-12-13 06:42
浏览 78
已采纳

如何在golang中初始化以下结构的结构

I have the following data structure. I need to initialize it without using nested initialization. This data structure will be flushed to output a json file later.

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

Problem is when I try to append the variable of type struct2 to the Attack_resources[] slice, it gives the error as

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

How can we initialize the struct without using new or any ptr? As, if we use any of the standard struct initialization technique, it will give the above error. If I change the above data structure and make it hold a pointer to another struct, it doesn't store the values correctly. I am very new to golang. Any help is appreciated. Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dongshi1102 2016-12-13 07:06
    关注

    You can initialize a struct value using:

    resource := struct2{}
    

    As @nothingmuch pointed out, if you have a struct pointer and need the underlying value, you can dereference the pointer using:

    deref := *resource
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?