Reputation: 1130
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
}
Upvotes: 0
Views: 227
Reputation: 332
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"
}
}
}
Upvotes: 1