English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic Tutorial in Golang

Control Statements in Golang

Functions & Methods in Golang

Structs in Golang

Slices & Arrays in Golang

Strings(String) in Golang

Pointers in Golang

Interfaces in Golang

Concurrency in Golang

Golang Exception(Error)

Other Miscellaneous in Golang

Go Nested Struct

StructureIn Golang, it is a user-defined type that allows us to create a set of different types of elements in a unit. Any real entity that has a set of properties or fields can be represented as a structure. Go language allows nested structures. A structure that is a field of another structure is called a nested structure. In other words, a structure within another structure is called a nested structure.

Syntax:

type struct_name_1 struct{}}
  // Fields
} 
type struct_name_2 struct{}}
  variable_name  struct_name_1
}

Let's discuss this concept with an example:

//Nested structure 
package main 
  
import "fmt"
  
//Create structure
type Author struct { 
    name   string 
    branch string 
    year   int
} 
  
//Create nested structure
type HR struct { 
  
    //Field structure
    details Author 
} 
  
func main() { 
  
    // Initialize structure fields 
    result := HR{       
        details: Author{"Sona", "ECE", 2013, 
    } 
  
    //Print output values
    fmt.Println("\nAuthor's detailed information") 
    fmt.Println(result) 
}

Output:

Author's detailed information
{{Sona ECE 2013}}

Nested structure example2:

package main 
  
import "fmt"
  
//Create structure 
type Student struct { 
    name   string 
    branch string 
    year   int
} 
  
//Create nested structure
type Teacher struct { 
    name    string 
    subject string 
    exp     int
    details Student 
} 
  
func main() { 
  
    //Initialize structure fields
    result := Teacher{ 
        name:    "Suman", 
        subject: "Java", 
        exp:     5, 
        details: Student{"Bongo", "CSE", 2, 
    } 
   
    fmt.Println("Teacher's detailed information") 
    fmt.Println("Teacher's name: ", result.name) 
    fmt.Println("Subject: ", result.subject) 
    fmt.Println("Experience: ", result.exp) 
  
    fmt.Println("\nStudent's detailed information") 
    fmt.Println("Student's name: ", result.details.name) 
    fmt.Println("Student's department name: ", result.details.branch) 
    fmt.Println("Age: ", result.details.year) 
}

Output:

Teacher's detailed information
Teacher's name:  Suman
Subject:  Java
Experience:  5
Student's detailed information
Student's name:  Bongo
Student's department name:  CSE
Age:  2