더북(TheBook)

익명 인터페이스

인터페이스도 타입으로 정의하지 않고 익명으로 사용할 수 있다

func display(s interface { show() }) {
    s.show()
}

display() 함수의 매개변수 타입을 interface { show() }로 정의했다. display() 함수에는 show() 메서드를 가진 타입을 매개변수로 전달할 수 있다.

type rect struct{ width, height float64 }
 
func (r rect) show() {
    fmt.Printf(“width: %f, height: %f\n”, r.width, r.height)
}
 
type circle struct{ radius float64 }
 
func (c circle) show() {
    fmt.Printf(“radius: %f\n”, c.radius)
}
 
func main() {
    r := rect{3, 4}
    c := circle{2.5}
    display(r)        // width: 3.000000, height: 4.000000
    display(c)        // radius: 2.500000
}

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.