Methods

When you attach a func to a type the func becomes a method of that type. So, it can be called through that type. Go will pass the type (the receiver) to the method when it’s called.

Example

Create a new counter type and attach a method to it:

type Count int func (c Count) Incr() int {

c = c + 1

return int(c)

}

The method above is similar to this func:

func Incr(c Count) int

Not exactly true but you can think of the methods as above

Value receiver

The value of the Count instance is copied and passed to the method when it’s called.

var c Count; c.Incr(); c.Incr() // output: 1 1

It doesn’t increase because “c” is a value-receiver.

Pointer receiver

To increase the counter’s value you need to attach the Incr func to the Count pointer type — *Count .

func (c *Count) Incr() int {

*c = *c + 1

return int(*c)

} var c Count c.Incr(); c.Incr() // output: 1 2