我是刚开始高朗开发的。我试图初始化一个具有3级嵌入式结构的结构。我可以创建到2级,但是当我尝试使用第3级时,它会给我这个编译时错误。
复合文字中的缺失类型
这是可用的试用代码。请帮助/建议一个很好的方法来实现同样的目标。
在main.go中,无法初始化a2变量。
package main
import (
"structpackage"
cfmt "basic/utils"
"fmt"
)
type p StrPackage
type n NestedStruct
type Address struct {
Name string
city string
Pincode int
StrPackage p // embedded struct
NestedStruct n // nested struct embedded in Address struct
}
func main() {
// Declaring and initializing a struct using a struct literal
a1 := Address{Name: "Akshay", city: "Dehradun", Pincode: 3623572, StrPackage: p{14, "Software engineer"}} // embedded struct implementation
/** * embedded struct implementation Start **/
a2 := Address{Name: "Akshay", city: "Dehradun", Pincode: 3623572, NestedStruct: n{Designation: "Software engineer", S: {Age: 12, Occuption: "sfdsf"}}} // Naming fields while initializing a struct
fmt.Println("Address2: ", a2)
}structpackage.go
package structpackage
type StrPackage struct {
Age int
Occuption string
}
type NestedStruct struct {
Designation string
S StrPackage
}发布于 2022-11-22 03:46:08
注意,Strpackage类型的对象需要动态构造并分配给NestedStruct.S。
a2 := Address{
Name: "Akshay",
city: "Dehradun",
Pincode: 3623572,
NestedStruct: n{
Designation: "Software engineer",
S: structpackage.StrPackage{
Age: 12, Occuption:
"sfdsf"
}
}
}https://stackoverflow.com/questions/73350654
复制相似问题