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.
func (c *Counter) inc ()
| | | |
| | | +-- parameters: none
| | +-- method name
| +-- THE RECEIVER = this, named by you, typed explicitly
+-- keywordPointer 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.
- Use a pointer receiver by default: it can mutate, and it avoids copying the struct.
- Be consistent — do not mix value and pointer receivers on the same type.
- You can define methods on any named type you own, not just structs: type Celsius float64 can have methods.
- type Foo struct{} is a zero-field type. It exists purely to hang methods on and occupies 0 bytes.