Advertisement
cwchen

[Go] Creating a Point class with methods.

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