Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Methods are allow us to create functions on types
- type Coord struct { X, Y int32 }
- // They require a receiver argument between the keyword and name
- // Define a function that expects a Coord type named c, is named Combine, and will return a 32 bit int
- func (c Coord) Combine() int32 {
- return c.X + c.Y
- }
- ...
- a := Coord{5, 2}
- b := a.Combine() // 7
- // We can pass in a pointer of our type to operate directly upon it
- func (c *Coord) Double() {
- c.X = c.X * 2
- c.Y = c.Y * 2
- }
- ...
- a := Coord(5, 2}
- a.Double() // {10 4}
- // We can't overload primitives
- // We can, however, extend them
- type NewFloat float64
- func (nf NewFloat) Double() NewFloat {
- return nf * NewFloat(2)
- }
- ...
- f := NewFloat(5)
- f = f.Double() // 10
- // For comparison
- type Coord struct{ X, Y int32 }
- func (c *Coord) Double() {
- c.X = c.X * 2
- c.Y = c.Y * 2
- }
- func Double(c *Coord) {
- c.X = c.X * 2
- c.Y = c.Y * 2
- }
- ...
- c := Coord{5, 3}
- c.Double()
- // Is the same as
- Double(&c)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement