import (
"fmt"
"math"
)
type shape interface {
area() (float64, string)
}
type circle struct {
radius float64
name string
}
type rect struct {
width float64
height float64
name string
}
func (r rect) area() (float64, string) {
return r.width * r.height,
r.name
}
func (c circle) area() (float64, string) {
return math.Pi * c.radius * c.radius,
c.name
}
func main() {
c1 := circle{4, "circle1"}
r1 := rect{5, 6, "rectangle1"}
shapes := []shape{c1, r1}
for _, shape := range shapes {
area, name := shape.area()
fmt.Println(name, "area is: ", area)
}
}
//cmd
C:\Users\bob\golang1>go run tutorial.go
circle1 area is: 50.26548245743669
rectangle1 area is: 30
reference:
No comments:
Post a Comment