interfaces_ext.go 826 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package main
  2. import "fmt"
  3. type Square struct {
  4. side float32
  5. }
  6. type Triangle struct {
  7. base float32
  8. height float32
  9. }
  10. type AreaInterface interface {
  11. Area() float32
  12. }
  13. type PeriInterface interface {
  14. Perimeter() float32
  15. }
  16. func main() {
  17. var areaIntf AreaInterface
  18. var periIntf PeriInterface
  19. sq1 := new(Square)
  20. sq1.side = 5
  21. tr1 := new(Triangle)
  22. tr1.base = 3
  23. tr1.height = 5
  24. areaIntf = sq1
  25. fmt.Printf("The square has area: %f\n", areaIntf.Area())
  26. periIntf = sq1
  27. fmt.Printf("The square has perimeter: %f\n", periIntf.Perimeter())
  28. areaIntf = tr1
  29. fmt.Printf("The triangle has area: %f\n", areaIntf.Area())
  30. }
  31. func (sq *Square) Area() float32 {
  32. return sq.side * sq.side
  33. }
  34. func (sq *Square) Perimeter() float32 {
  35. return 4 * sq.side
  36. }
  37. func (tr *Triangle) Area() float32 {
  38. return 0.5 * tr.base * tr.height
  39. }