interfaces_poly.go 877 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // interfaces_poly.go
  2. package main
  3. import "fmt"
  4. type Shaper interface {
  5. Area() float32
  6. }
  7. type Square struct {
  8. side float32
  9. }
  10. func (sq *Square) Area() float32 {
  11. return sq.side * sq.side
  12. }
  13. type Rectangle struct {
  14. length, width float32
  15. }
  16. func (r Rectangle) Area() float32 {
  17. return r.length * r.width
  18. }
  19. func main() {
  20. r := Rectangle{5, 3} // Area() of Rectangle needs a value
  21. q := &Square{5} // Area() of Square needs a pointer
  22. shapes := []Shaper{r, q}
  23. fmt.Println("Looping through shapes for area ...")
  24. for n, _ := range shapes {
  25. fmt.Println("Shape details: ", shapes[n])
  26. fmt.Println("Area of this shape is: ", shapes[n].Area())
  27. }
  28. }
  29. /* Output:
  30. Looping through shapes for area ...
  31. Shape details: {5 3}
  32. Area of this shape is: 15
  33. Shape details: &{5}
  34. Area of this shape is: 25
  35. */