Menu
CoddyTech

임베디드 구조체

Coddy GO 여정의 기초 섹션에 포함된 레슨. 109개 중 99번째.

Go에서는 하나의 구조체를 다른 구조체 안에 포함하여 컴포지션 관계를 만들 수 있습니다. 이것이 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
challenge icon

챌린지

초급

이 과제에서는 Go에서 임베디드 구조체(컴포지션)를 사용하는 방법을 연습합니다.

두 개의 구조체 Address와 Person이 있습니다. 사람이 주소 필드에 직접 접근할 수 있도록 Person 구조체에 Address 구조체를 임베드해야 합니다.

여러분의 과제는 Address 구조체를 임베드하도록 Person 구조체 정의를 완성하는 것입니다. main의 출력문은 이미 사람 객체에서 주소 필드(person.Street, person.City, person.ZipCode)를 직접 읽습니다. Address를 임베드하면 이 코드가 컴파일됩니다.

직접 해보기

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)
	
	// person 인스턴스에서 주소 필드를 직접 출력합니다
	fmt.Println("Street:", person.Street)
	fmt.Println("City:", person.City)
	fmt.Println("ZipCode:", person.ZipCode)
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

기초의 모든 레슨

직접 연습해 보세요: 온라인 Go 컴파일러