0

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

1

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"
            }
         }
     }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.