Advertisement
cwchen

[Go] Point class with static methods

Oct 5th, 2017
1,228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.67 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "log"
  5.     "math"
  6. )
  7.  
  8. type Point struct {
  9.     x float64
  10.     y float64
  11. }
  12.  
  13. func NewPoint(x float64, y float64) *Point {
  14.     p := new(Point)
  15.  
  16.     p.SetX(x)
  17.     p.SetY(y)
  18.  
  19.     return p
  20. }
  21.  
  22. func (p *Point) X() float64 {
  23.     return p.x
  24. }
  25.  
  26. func (p *Point) Y() float64 {
  27.     return p.y
  28. }
  29.  
  30. func (p *Point) SetX(x float64) {
  31.     p.x = x
  32. }
  33.  
  34. func (p *Point) SetY(y float64) {
  35.     p.y = y
  36. }
  37.  
  38. func Dist(p1 *Point, p2 *Point) float64 {
  39.     xSqr := math.Pow(p1.X()-p2.X(), 2)
  40.     ySqr := math.Pow(p1.Y()-p2.Y(), 2)
  41.  
  42.     return math.Sqrt(xSqr + ySqr)
  43. }
  44.  
  45. func main() {
  46.     p1 := NewPoint(0, 0)
  47.     p2 := NewPoint(3.0, 4.0)
  48.  
  49.     if !(Dist(p1, p2) == 5.0) {
  50.         log.Fatal("Wrong value")
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement