임베디드 구조체
Coddy GO 여정의 기초 섹션에 포함된 레슨 — 109개 중 99번째.
Go는 하나의 구조체(struct)를 다른 구조체 내부에 임베드하여 구성(composition) 관계를 만들 수 있게 해줍니다. 이것이 상속에 대한 Go의 접근 방식입니다.
하나가 다른 하나에 포함된 두 개의 구조체를 정의합니다:
type Address struct {
city string
state string
}
type Person struct {
name string
age int
Address // 임베디드 구조체 (필드 이름 없음)
}
func main() {
person := Person{
name: "Alice",
age: 30,
Address: Address{city: "Portland", state: "Oregon"},
}
// 필드에 직접 접근
fmt.Println(person.city) // 임베디드 필드에 접근
}
출력 결과는 임베디드 구조체의 필드에 직접 접근할 수 있음을 보여줍니다:
Portland챌린지
초급이 챌린지에서는 Go에서 임베디드 구조체(컴포지션)를 사용하는 연습을 합니다.
두 개의 구조체 Address와 Person이 있습니다. Person 구조체는 Address 구조체를 임베드하여 사용자가 주소 필드에 직접 접근할 수 있도록 해야 합니다.
여러분의 과제는 Address 구조체를 임베드하도록 Person 구조체 정의를 완성하고, person 인스턴스에서 주소 필드에 직접 접근하는 것입니다.
치트 시트
Go는 구성을 위해 구조체 임베딩(struct embedding)을 사용합니다. 필드 이름 없이 구조체 타입을 포함하여 하나의 구조체를 다른 구조체 내부에 임베딩합니다:
type Address struct {
city string
state string
}
type Person struct {
name string
age int
Address // 임베딩된 구조체 (필드 이름 없음)
}
임베딩된 구조체 필드에 직접 접근하기:
person := Person{
name: "Alice",
age: 30,
Address: Address{city: "Portland", state: "Oregon"},
}
fmt.Println(person.city) // 임베딩된 필드에 직접 접근
직접 해보기
package main
import "fmt"
// Address 구조체는 위치 정보를 포함합니다
type Address struct {
Street string
City string
ZipCode string
}
// Person 구조체는 Address 구조체를 임베딩해야 합니다
type Person struct {
Name string
Age int
// TODO: 여기에 Address 구조체를 임베딩하세요 (한 줄만 작성)
}
func main() {
// 주소 정보를 포함한 새로운 person을 생성합니다
person := Person{
Name: "Alice",
Age: 30,
Address: Address{
Street: "123 Main St",
City: "Wonderland",
ZipCode: "12345",
},
}
// 주소를 포함한 person 정보를 출력합니다
fmt.Println("Name:", person.Name)
fmt.Println("Age:", person.Age)
// TODO: person 인스턴스에서 직접 주소 필드들을 출력하세요
// (person.Address.Street 등을 사용하지 않고)
fmt.Println("Street:", person.Street)
fmt.Println("City:", person.City)
fmt.Println("ZipCode:", person.ZipCode)
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
기초의 모든 레슨
2변수와 기본 자료형
변수란 무엇인가`:=`를 이용한 타입 추론정수 (int)부동 소수점 수불리언 (Booleans)문자열 (Strings)제로 값 (Zero Values)상수명명 규칙요약 - 변수와 타입