how to initialize the struct of following structure in golang

huangapple go评论102阅读模式
英文:

how to initialize the struct of following structure in golang

问题

我有以下的数据结构。我需要在不使用嵌套初始化的情况下对其进行初始化。这个数据结构将被刷新以输出一个json文件。

  1. type GeneratePlan struct{
  2. Mode string `json:"mode"`
  3. Name string `json:"name"`
  4. Schema string `json:"schema"`
  5. Version string `json:"version"`
  6. Attack_plans []struct1 `json:"attack-plans"`
  7. }
  8. type struct1 struct {
  9. Attack_plan Attack_plan `json:"attack-plan"`
  10. }
  11. type Attack_plan struct{
  12. Attack_resouces []struct2 `json:"attack-resources"`
  13. }
  14. type struct2 struct {
  15. Attack_resource Attack_resource `json:"attack-resource"`
  16. }

问题是,当我尝试将类型为struct2的变量追加到Attack_resources[]切片时,它会报错:

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

我们如何在不使用new或任何指针的情况下初始化结构体?因为如果我们使用任何标准的结构体初始化技术,它都会产生上述错误。
如果我更改上述数据结构并使其持有指向另一个结构体的指针,它不会正确存储值。我对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.

  1. type GeneratePlan struct{
  2. Mode string `json:"mode"`
  3. Name string `json:"name"`
  4. Schema string `json:"schema"`
  5. Version string `json:"version"`
  6. Attack_plans []struct1 `json:"attack-plans"`
  7. }
  8. type struct1 struct {
  9. Attack_plan Attack_plan `json:"attack-plan"`
  10. }
  11. type Attack_plan struct{
  12. Attack_resouces []struct2 `json:"attack-resources"`
  13. }
  14. type struct2 struct {
  15. Attack_resource Attack_resource `json:"attack-resource"`
  16. }

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

  1. 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

得分: 0

你可以使用以下方式初始化一个结构体的值:

  1. resource := struct2{}

正如 @nothingmuch 指出的那样,如果你有一个结构体指针并且需要获取底层的值,你可以使用解引用操作符来解引用指针:

  1. deref := *resource
英文:

You can initialize a struct value using:

  1. resource := struct2{}

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

  1. deref := *resource

huangapple
  • 本文由 发表于 2016年12月13日 14:42:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/41115055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定