multi_interfaces_poly.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //multi_interfaces_poly.go
  2. package main
  3. import "fmt"
  4. type Shaper interface {
  5. Area() float32
  6. }
  7. type TopologicalGenus interface {
  8. Rank() int
  9. }
  10. type Square struct {
  11. side float32
  12. }
  13. func (sq *Square) Area() float32 {
  14. return sq.side * sq.side
  15. }
  16. func (sq *Square) Rank() int {
  17. return 1
  18. }
  19. type Rectangle struct {
  20. length, width float32
  21. }
  22. func (r Rectangle) Area() float32 {
  23. return r.length * r.width
  24. }
  25. func (r Rectangle) Rank() int {
  26. return 2
  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. shapes := []Shaper{r, q}
  32. fmt.Println("Looping through shapes for area ...")
  33. for n, _ := range shapes {
  34. fmt.Println("Shape details: ", shapes[n])
  35. fmt.Println("Area of this shape is: ", shapes[n].Area())
  36. }
  37. topgen := []TopologicalGenus{r, q}
  38. fmt.Println("Looping through topgen for rank ...")
  39. for n, _ := range topgen {
  40. fmt.Println("Shape details: ", topgen[n])
  41. fmt.Println("Topological Genus of this shape is: ", topgen[n].Rank())
  42. }
  43. }
  44. /* Output:
  45. Looping through shapes for area ...
  46. Shape details: {5 3}
  47. Area of this shape is: 15
  48. Shape details: &{5}
  49. Area of this shape is: 25
  50. Looping through topgen for rank ...
  51. Shape details: {5 3}
  52. Topological Genus of this shape is: 2
  53. Shape details: &{5}
  54. Topological Genus of this shape is: 1
  55. */