interfaces_poly2.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // interfaces_poly2.go
  2. package main
  3. import (
  4. "fmt"
  5. "math"
  6. )
  7. type Shaper interface {
  8. Area() float32
  9. }
  10. type Square struct {
  11. side float32
  12. }
  13. func (sq *Square) Area() float32 {
  14. return sq.side * sq.side
  15. }
  16. type Rectangle struct {
  17. length, width float32
  18. }
  19. func (r Rectangle) Area() float32 {
  20. return r.length * r.width
  21. }
  22. type Circle struct {
  23. radius float32
  24. }
  25. func (c *Circle) Area() float32 {
  26. return math.Pi * c.radius * c.radius
  27. }
  28. func main() {
  29. r := Rectangle{5, 3} // Area() of Rectangle needs a value
  30. q := &Square{5} // Area() of Square needs a pointer
  31. c := &Circle{2.5}
  32. fmt.Println("Looping through shapes for area ...")
  33. // shapes := []Shaper{Shaper(r), Shaper(q), Shaper(c)}
  34. shapes := []Shaper{r, q, c}
  35. for n := range shapes {
  36. fmt.Println("Shape details: ", shapes[n])
  37. fmt.Println("Area of this shape is: ", shapes[n].Area())
  38. }
  39. }
  40. /* Output:
  41. Looping through shapes for area ...
  42. Shape details: {5 3}
  43. Area of this shape is: 15
  44. Shape details: &{5}
  45. Area of this shape is: 25
  46. Shape details: &{2.5}
  47. Area of this shape is: 19.634954
  48. */