package main
import (
"fmt"
"math"
)
type Shape struct {
Name string
Area func() float64
}
func (s Shape) GetArea() float64 {
return s.Area()
}
func main() {
triangle := Shape{
Name: "Triangle",
Area: func() float64 {
base := 10.0
height := 5.0
return 0.5 * base * height
},
}
rectangle := Shape{
Name: "Rectangle",
Area: func() float64 {
length := 10.0
width := 5.0
return length * width
},
}
circle := Shape{
Name: "Circle",
Area: func() float64 {
radius := 5.0
return math.Pi * radius * radius
},
}
shapes := []Shape{triangle, rectangle, circle}
for _, shape := range shapes {
fmt.Printf("%s area: %f\n", shape.Name, shape.GetArea())
}
}
/*type Shape struct {
Name string
Area func() float64
}
func TriangleArea(base float64, height float64) float64 {
return 0.5 * base * height
}
func RectangleArea(length float64, width float64) float64 {
return length * width
}
func CircleArea(radius float64) float64 {
return math.Pi * radius * radius
}
func main() {
triangle := Shape{Name: "Triangle", Area: func() float64 {
return TriangleArea(5, 10)
}}
rectangle := Shape{Name: "Rectangle", Area: func() float64 {
return RectangleArea(5, 10)
}}
circle := Shape{Name: "Circle", Area: func() float64 {
return CircleArea(5)
}}
shapes := []Shape{triangle, rectangle, circle}
for _, shape := range shapes {
fmt.Printf("The area of %s is %f\n", shape.Name, shape.Area())
}
}
*/