英文:
GoLang Level3 embedded struct initialisation
问题
我是你的中文翻译助手,以下是你要翻译的内容:
我对Golang开发还很陌生。我试图初始化一个包含三级嵌套结构的结构体。我可以创建两级嵌套,但是当我尝试使用三级嵌套时,编译时会出现以下错误:
在复合字面量中缺少类型
以下是试验代码,请帮助/建议一个优秀的方法来实现相同的功能。
在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 // 嵌套结构体
NestedStruct n // 嵌套在Address结构体中的结构体
}
func main() {
// 使用结构体字面量声明和初始化结构体
a1 := Address{Name: "Akshay", city: "Dehradun", Pincode: 3623572, StrPackage: p{14, "Software engineer"}} // 嵌套结构体的实现
/** * 嵌套结构体的实现开始 **/
a2 := Address{Name: "Akshay", city: "Dehradun", Pincode: 3623572, NestedStruct: n{Designation: "Software engineer", S: {Age: 12, Occuption: "sfdsf"}}} // 在初始化结构体时命名字段
fmt.Println("Address2: ", a2)
}
structpackage.go
package structpackage
type StrPackage struct {
Age int
Occuption string
}
type NestedStruct struct {
Designation string
S StrPackage
}
希望对你有所帮助!
英文:
I am new to Golang development. I was trying to initialize a struct which has a level 3 embedded struct. I can create till 2 levels, but when I try with level 3, it gives me this compile time error.
missing type in composite literal
Here is the trial code
available. Please help/suggest an excellent way to achieve the same.
In main.go, unable to initialise a2 variable.
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
}
答案1
得分: 1
请注意,需要在运行时构造一个类型为Strpackage的对象,并将其赋值给NestedStruct.S。
a2 := Address{
Name: "Akshay",
city: "Dehradun",
Pincode: 3623572,
NestedStruct: n{
Designation: "Software engineer",
S: structpackage.StrPackage{
Age: 12,
Occuption: "sfdsf"
}
}
}
请注意,上述代码中的字符串部分已经翻译为中文。
英文:
Notice that an object of type Strpackage needs to be constructed on the fly and assigned to NestedStruct.S
a2 := Address{
Name: "Akshay",
city: "Dehradun",
Pincode: 3623572,
NestedStruct: n{
Designation: "Software engineer",
S: structpackage.StrPackage{
Age: 12, Occuption:
"sfdsf"
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论