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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 鼠标右键,撤销删除 复制 移动,要怎样删除
  • ¥15 使用MATLAB进行余弦相似度计算加速
  • ¥15 服务器安装php5.6版本
  • ¥15 我想用51单片机和数码管做一个从0开始的计数表 我写了一串代码 但是放到单片机里面数码管只闪烁一下然后熄灭
  • ¥20 系统工程中,状态空间模型中状态方程的应用。请猛男来完整讲一下下面所有问题
  • ¥15 我想在WPF的Model Code中获取ViewModel Code中的一个参数
  • ¥15 arcgis处理土地利用道路 建筑 林地分类
  • ¥20 使用visual studio 工具用C++语音,调用openslsx库读取excel文件的sheet问题
  • ¥100 寻会做云闪付tn转h5支付链接的技术
  • ¥15 DockerSwarm跨节点无法访问问题