Golang中的嵌套结构代码示例解释

2021年3月17日14:46:27 发表评论 793 次浏览

一种结构或结构在Golang中, 这是一种用户定义的类型, 它使我们可以将一组不同类型的元素创建到一个单元中。具有一组属性或字段的任何现实世界实体都可以表示为结构。 Go语言允许嵌套结构。作为另一结构领域的结构称为嵌套结构。换句话说, 另一个结构中的结构称为嵌套结构。

语法如下:

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

}

让我们借助示例来讨论这个概念:

范例1:

// Golang program to illustrate
// the nested structure
package main
  
import "fmt"
  
// Creating structure
type Author struct {
     name   string
     branch string
     year   int
}
  
// Creating nested structure
type HR struct {
  
     // structure as a field
     details Author
}
  
func main() {
  
     // Initializing the fields
     // of the structure
     result := HR{
      
         details: Author{ "Sona" , "ECE" , 2013}, }
  
     // Display the values
     fmt.Println( "\nDetails of Author" )
     fmt.Println(result)
}

输出如下:

Details of Author
{{Sona ECE 2013}}

范例2:

// Golang program to illustrate
// the nested structure
package main
  
import "fmt"
  
// Creating structure
type Student struct {
     name   string
     branch string
     year   int
}
  
// Creating nested structure
type Teacher struct {
     name    string
     subject string
     exp     int
     details Student
}
  
func main() {
  
     // Initializing the fields
     // of the structure
     result := Teacher{
         name:    "Suman" , subject: "Java" , exp :     5, details: Student{ "Bongo" , "CSE" , 2}, }
  
     // Display the values
     fmt.Println( "Details of the Teacher" )
     fmt.Println( "Teacher's name: " , result.name)
     fmt.Println( "Subject: " , result.subject)
     fmt.Println( "Experience: " , result. exp )
  
     fmt.Println( "\nDetails of Student" )
     fmt.Println( "Student's name: " , result.details.name)
     fmt.Println( "Student's branch name: " , result.details.branch)
     fmt.Println( "Year: " , result.details.year)
}

输出如下:

Details of the Teacher
Teacher's name:  Suman
Subject:  Java
Experience:  5

Details of Student
Student's name:  Bongo
Student's branch name:  CSE
Year:  2

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: