How to Initialize a Nested Struct in Golang

To initialize a nested struct, you can specify the values for the fields of the outer and nested struct using a struct literal.

Here’s an example of how to initialize a nested struct.

package main

import (
  "fmt"
)

type Address struct {
  Street string
  City string
  State string
  Zip string
}

type Student struct {
  Name string
  Rollno int
  Address Address
}

func main() {
  s := Student{
    Name: "Krunal Lathiya",
    Rollno: 30,
    Address: Address{
    Street: "123 Main St",
    City: "New York",
    State: "NY",
    Zip: "20001",
   },
 }

 fmt.Printf("Student: %+v\n", s)
}

Output

Student: {
          Name:Krunal Lathiya 
          Rollno:30 
          Address:{
               Street:123 Main St 
               City:New York 
               State:NY Zip:20001
          }
}

In this example, we defined two structs: Address and Student.

The Student struct has a nested Address struct as a field.

We initialized the Student struct s using a struct literal, providing values for the Name, Rollno, and Address fields.

We initialize the nested Address struct inside the Address field using another struct literal, specifying the values for the Street, City, State, and Zip fields.

Finally, we printed the initialized Student struct s using the %+v format specifier, which includes field names in the output.

That’s it.

Leave a Comment