英文:
how to initialize the struct of following structure in golang
问题
我有以下的数据结构。我需要在不使用嵌套初始化的情况下对其进行初始化。这个数据结构将被刷新以输出一个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或任何指针的情况下初始化结构体?因为如果我们使用任何标准的结构体初始化技术,它都会产生上述错误。
如果我更改上述数据结构并使其持有指向另一个结构体的指针,它不会正确存储值。我对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
得分: 0
你可以使用以下方式初始化一个结构体的值:
resource := struct2{}
正如 @nothingmuch 指出的那样,如果你有一个结构体指针并且需要获取底层的值,你可以使用解引用操作符来解引用指针:
deref := *resource
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论