메서드 재사용
구조체 임베딩의 편리한 점은 임베디드 필드가 포함된 구조체에서 임베디드 필드에 정의된 메서드를 그대로 사용할 수 있다는 것이다.
다음 코드를 보자. 먼저 Item 구조체와 Cost() 메서드를 정의하고 Item을 DiscountItem의 임베디드 필드로 지정한다. main 함수에서는 DiscountItem 타입인 eventShoes에서 Item 타입에 정의된 Cost() 메서드를 호출한다.
type Item struct { name string price float64 quantity int } func (t Item) Cost() float64 { return t.price * float64(t.quantity) } type DiscountItem struct { Item discountRate float64 } func main() { shoes := Item{"Women's Walking Shoes", 30000, 2} eventShoes := DiscountItem{ Item{"Sports Shoes", 50000, 3}, 10.00, } fmt.Println(shoes.Cost()) // 60000 fmt.Println(eventShoes.Cost()) // 150000 }
DiscountItem 타입에는 Cost() 메서드가 정의되어 있지 않지만, DiscountItem의 임베디드 필드인 Item에는 Cost() 메서드가 정의되어 있으므로 DiscountItem에서도 Cost() 메서드를 사용할 수 있다.