Go에서 interface는 method의 집합체다.
type Shape interface {
area() float64
perimeter() float64
}
//Rect 정의
type Rect struct {
width, height float64
}
//Circle 정의
type Circle struct {
radius float64
}
//Rect 타입에 대한 Shape 인터페이스 구현
func (r Rect) area() float64 { return r.width * r.height }
func (r Rect) perimeter() float64 {
return 2 * (r.width + r.height)
}
//Circle 타입에 대한 Shape 인터페이스 구현
func (c Circle) area() float64 {
return math.Pi * c.radius * c.radius
}
func (c Circle) perimeter() float64 {
return 2 * math.Pi * c.radius
}
func main() {
r := Rect{10., 20.}
c := Circle{10}
showArea(r, c)
}
func showArea(shapes ...Shape) {
for _, s := range shapes {
a := s.area() //인터페이스 메서드 호출
println(a)
}
}
Shape은 area()와 perimeter()를 가지고 있는 interface로
area()와 perimeter() method 모두 가지고 있는 struct를
Shape으로 사용할 수 있다.
출처 : http://golang.site/go/article/18-Go-%EC%9D%B8%ED%84%B0%ED%8E%98%EC%9D%B4%EC%8A%A4