point_methods.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // float64 is necessary as input to math.Sqrt()
  2. package main
  3. import (
  4. "fmt"
  5. "math"
  6. )
  7. type Point struct {
  8. X, Y float64
  9. }
  10. func (p *Point) Scale(s float64) {
  11. p.X *= s
  12. p.Y *= s
  13. }
  14. func (p *Point) Abs() float64 {
  15. return math.Sqrt(float64(p.X*p.X + p.Y*p.Y))
  16. }
  17. type Point3 struct {
  18. X, Y, Z float64
  19. }
  20. func (p *Point3) Abs() float64 {
  21. return math.Sqrt(float64(p.X*p.X + p.Y*p.Y + p.Z*p.Z))
  22. }
  23. type Polar struct {
  24. R, T float64
  25. }
  26. func (p Polar) Abs() float64 { return p.R }
  27. func main() {
  28. p1 := new(Point)
  29. p1.X = 3
  30. p1.Y = 4
  31. fmt.Printf("The length of the vector p1 is: %f\n", p1.Abs())
  32. p2 := &Point{4, 5}
  33. fmt.Printf("The length of the vector p2 is: %f\n", p2.Abs())
  34. p1.Scale(5)
  35. fmt.Printf("The length of the vector p1 after scaling is: %f\n", p1.Abs())
  36. fmt.Printf("Point p1 after scaling has the following coordinates: X %f - Y %f", p1.X, p1.Y)
  37. }
  38. /* Output:
  39. The length of the vector p1 is: 5.000000
  40. The length of the vector p2 is: 6.403124
  41. The length of the vector p1 after scaling is: 25.000000
  42. Point p1 after scaling has the following coordinates: X 15.000000 - Y 20.000000
  43. */