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

Golang 기본 튜토리얼

Golang 제어문

Golang 함수 & 메서드

Golang 구조체

Golang 슬라이스 & 배열

Golang 문자열(String)

Golang 포인터

Golang 인터페이스

Golang 병행

Golang 예외(Error)

Golang 기타Miscellaneous

Go 내장 구조체

구조체Golang에서는 사용자 정의된 타입으로, 하나의 단위에서 다양한 타입의 요소를 생성할 수 있습니다. 특정 속성이나 필드를 가진 실제 실체는 구조체로 표현될 수 있습니다. Go 언어는 구조체를 내장할 수 있습니다. 하나의 구조체는 다른 구조체의 필드로 사용되며, 이를 내장 구조체라고 합니다. 다시 말해, 다른 구조체 내에 있는 구조체는 내장 구조체라고 합니다.

문법:

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

이 개념을 설명하기 위해 예제를 사용해 보겠습니다:

//내장 구조체 
package main 
  
import "fmt"
  
//구조체 생성
type Author struct { 
    name   string 
    branch string 
    year   int
} 
  
//내장 구조체 생성
type HR struct { 
  
    //필드 구조
    details Author 
} 
  
func main() { 
  
    // 구조체 필드 초기화 
    result := HR{       
        details: Author{"Sona", "ECE", 2013, 
    } 
  
    //출력 값을 출력
    fmt.Println("\n저자의 상세 정보") 
    fmt.Println(result) 
}

출력:

저자의 상세 정보
{{Sona ECE 2013}}

내장 구조체 예제2:

package main 
  
import "fmt"
  
//구조 생성 
type Student struct { 
    name   string 
    branch string 
    year   int
} 
  
//내장 구조 생성
type Teacher struct { 
    name    string 
    subject string 
    exp     int
    details Student 
} 
  
func main() { 
  
    //구조 필드 초기화
    result := Teacher{ 
        name:    "Suman", 
        subject: "Java", 
        exp:     5, 
        details: Student{"Bongo", "CSE", 2, 
    } 
   
    fmt.Println("교사의 상세 사항") 
    fmt.Println("교사의 이름: ", result.name) 
    fmt.Println("학과: ", result.subject) 
    fmt.Println("경력: ", result.exp) 
  
    fmt.Println("\n학생의 상세 정보") 
    fmt.Println("학생의 이름: ", result.details.name) 
    fmt.Println("학생의 부서 이름: ", result.details.branch) 
    fmt.Println("연령: ", result.details.year) 
}

출력:

교사의 상세 사항
교사의 이름:  Suman
학과:  Java
경력:  5
학생의 상세 정보
학생의 이름:  Bongo
학생의 부서 이름:  CSE
연령:  2