Recent Comments
Link
Recent Posts
Today
Total
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
관리 메뉴

Study Memory Work

[Go Lang] 구조체 - 임베디드 패턴, 메소드 상속 활용, 오버라이딩 본문

Programing/Go

[Go Lang] 구조체 - 임베디드 패턴, 메소드 상속 활용, 오버라이딩

Hera Choi 2023. 3. 2. 16:41

구조체 임베디드 패턴

Go에는 상속 개념이 없는 대신 상속과 같은 기능을 하도록 하는 활용 패턴

A 구조체와  B구조체가 있고, B구조체가 A구조체를 필드로 가진 경우 --> A구조체 관련 리시버메소드까지 B구조체에서 구현이 가능하다.

package main

import "fmt"

// 사원
type Employee struct {
	name   string
	salary float64
	bonus  float64
}

// 임원 -------------------> 사원 구조체를 필드로 가지고 있음
type Excutives struct {
	Employee     // ---> "is a 관계"
	specialBonus float64
}

// 급여
func (e Employee) Calaulate() float64 {
	return e.salary + e.bonus
}

func main() {
	ep1 := Employee{"kim", 2000000, 150000}
	ep2 := Employee{"lee", 3000000, 300000}
	ep3 := Employee{"park", 5000000, 500000}

	ex := Excutives{ep3, 1000000}

	fmt.Println("ex 1 : ", int(ep1.Calaulate()))
	fmt.Println("ex 1 : ", int(ep2.Calaulate()))

	// Excutives.Employee.Calaulate() ---> Excutives는 Calaulate()와 직접적인 연관은 없지만
    //	내부 Employee가 Calaulate()을 가지고 있기 때문에 사용가능
	fmt.Println("ex 1 : ", int(ex.Calaulate()+ex.specialBonus))

}

 

구조체 임베디드 메소드 오버라이딩 패턴

같은 메소드명으로 다른 리시버메소드를 만들어 오버라이딩 형태로 활용할 수 있다.

package main

import "fmt"

// 사원
type employee struct {
	name   string
	salary float64
	bonus  float64
}

// 임원
type excutives struct {
	employee     // ---> is a 관계
	specialBonus float64
}

// 급여
func (e employee) calaulate() float64 {
	return e.salary + e.bonus
}

// 임원급여 ---------------------> 메소드 오버라이딩. 위와 메소드명은 같지만 리시버 구조체가 다름
func (ex excutives) calaulate() float64 {
	return ex.salary + ex.bonus + ex.specialBonus
}

func main() {
	ep1 := employee{"kim", 2000000, 150000}
	ep2 := employee{"lee", 3000000, 300000}
	ep3 := employee{"park", 5000000, 500000}

	ex := excutives{ep3, 1000000}

	fmt.Println("ex 2 : ", int(ep1.calaulate()))
	fmt.Println("ex 2 : ", int(ep2.calaulate()))

	// 오버라이딩 했기 때문에 excutives도 calaulate()를 가지고 있다
	fmt.Println("ex 2 : ", int(ex.calaulate()))

}