interface_poly3.go 1.2 KB

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