point_interfaces.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // float64 is necessary as input to math.Sqrt()
  2. package main
  3. import (
  4. "fmt"
  5. "math"
  6. )
  7. type Magnitude interface {
  8. Abs() float64
  9. }
  10. var m Magnitude
  11. type Point struct {
  12. X, Y float64
  13. }
  14. func (p *Point) Scale(s float64) {
  15. p.X *= s
  16. p.Y *= s
  17. }
  18. func (p *Point) Abs() float64 {
  19. return math.Sqrt(float64(p.X*p.X + p.Y*p.Y))
  20. }
  21. type Point3 struct {
  22. X, Y, Z float64
  23. }
  24. func (p *Point3) Abs() float64 {
  25. return math.Sqrt(float64(p.X*p.X + p.Y*p.Y + p.Z*p.Z))
  26. }
  27. type Polar struct {
  28. R, Theta float64
  29. }
  30. func (p Polar) Abs() float64 { return p.R }
  31. func main() {
  32. p1 := new(Point)
  33. p1.X = 3
  34. p1.Y = 4
  35. m = p1 // p1 is type *Point, has method Abs()
  36. fmt.Printf("The length of the vector p1 is: %f\n", m.Abs())
  37. p2 := &Point{4, 5}
  38. m = p2
  39. fmt.Printf("The length of the vector p2 is: %f\n", m.Abs())
  40. p1.Scale(5)
  41. m = p1
  42. fmt.Printf("The length of the vector p1 after scaling is: %f\n", m.Abs())
  43. fmt.Printf("Point p1 after scaling has the following coordinates: X %f - Y %f\n", p1.X, p1.Y)
  44. mag := m.Abs()
  45. m = &Point3{3, 4, 5}
  46. mag += m.Abs()
  47. m = Polar{2.0, math.Pi / 2}
  48. mag += m.Abs()
  49. fmt.Printf("The float64 mag is now: %f", mag)
  50. }
  51. /* Output:
  52. The length of the vector p1 is: 5.000000
  53. The length of the vector p2 is: 6.403124
  54. The length of the vector p1 after scaling is: 25.000000
  55. Point p1 after scaling has the following coordinates: X 15.000000 - Y 20.000000
  56. The float64 mag is now: 34.071068
  57. -- instead of:
  58. func (p *Point) Abs() float64 {
  59. return math.Sqrt(float64(p.X*p.X + p.Y*p.Y))
  60. }
  61. m = p1
  62. we can write:
  63. func (p Point) Abs() float64 {
  64. return math.Sqrt(float64(p.X*p.X + p.Y*p.Y))
  65. }
  66. m = p1
  67. and instead of:
  68. func (p Polar) Abs() float64 { return p.R }
  69. m = Polar{2.0, math.Pi / 2}
  70. we can write:
  71. func (p *Polar) Abs() float64 { return p.R }
  72. m = &Polar{2.0, math.Pi / 2}
  73. with the same output
  74. */