Advertisement
Koepnick

methods

Jan 15th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.99 KB | None | 0 0
  1. // Methods are allow us to create functions on types
  2.  
  3. type Coord struct { X, Y int32 }
  4.  
  5. // They require a receiver argument between the keyword and name
  6. // Define a function that expects a Coord type named c, is named Combine, and will return a 32 bit int
  7. func (c Coord) Combine() int32 {
  8.     return c.X + c.Y
  9. }
  10. ...
  11. a := Coord{5, 2}
  12. b := a.Combine()    // 7
  13.  
  14. // We can pass in a pointer of our type to operate directly upon it
  15. func (c *Coord) Double() {
  16.     c.X = c.X * 2
  17.     c.Y = c.Y * 2
  18. }
  19. ...
  20. a := Coord(5, 2}
  21. a.Double()         // {10 4}
  22.  
  23. // We can't overload primitives
  24. // We can, however, extend them
  25. type NewFloat float64
  26. func (nf NewFloat) Double() NewFloat {
  27.     return nf * NewFloat(2)
  28. }
  29. ...
  30. f := NewFloat(5)
  31. f = f.Double() // 10
  32.  
  33.  
  34.  
  35. // For comparison
  36. type Coord struct{ X, Y int32 }
  37.  
  38. func (c *Coord) Double() {
  39.     c.X = c.X * 2
  40.     c.Y = c.Y * 2
  41. }
  42.  
  43. func Double(c *Coord) {
  44.     c.X = c.X * 2
  45.     c.Y = c.Y * 2
  46. }
  47. ...
  48. c := Coord{5, 3}
  49. c.Double()
  50. // Is the same as
  51. Double(&c)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement