https://play.golang.org/p/YEK-6IWQ6Bw https://qiita.com/Nossa/items/a93024e653ff939115c6
GO 言語版です.
package main
import (
"fmt"
"math"
)
type shape interface {
area() float64
}
type triangle struct {
base float64
height float64
}
type circle struct {
radius float64
}
type rectangle struct {
width float64
height float64
}
func (t triangle) area() float64 {
return t.base * t.height / 2
}
func (c circle) area() float64 {
return c.radius * c.radius * math.Pi
}
func (r rectangle) area() float64 {
return r.width * r.height
}
func main() {
shapes := []shape{
triangle{base: 5, height: 4},
circle{radius: 3},
rectangle{width: 4, height: 4},
}
for _, shape := range shapes {
fmt.Printf("AREA: %f\n", shape.area())
}
}
出力結果
AREA: 10.000000
AREA: 28.274334
AREA: 16.000000