Section 2 of 11

Methods & receivers

A method is a function with an extra parameter list glued on the front.

In Java a method lives inside the class and `this` is invisible. In Go the type and its methods are separate declarations, and the receiver — Go’s `this` — is written explicitly in its own parens before the name. This is the only genuinely new syntax in the language.

anatomy
func   (c *Counter)   inc   ()
 |          |           |     |
 |          |           |     +-- parameters: none
 |          |           +-- method name
 |          +-- THE RECEIVER = this, named by you, typed explicitly
 +-- keyword

Pointer receiver vs value receiver

go.dev playground

Try it: Change `func (c *Counter) Inc()` to `func (c Counter) Inc()` and run again. The counter stops counting — a value receiver gets a copy.