Go Methods
In Go, a method is simply a function with a special "receiver" argument. This allows you to "attach" behavior to your custom types (usually structs).
Defining a Method
Pointer vs. Value Receivers
There are two ways to define methods:
- Value Receiver (
r rect): The method gets a copy of the struct. It cannot change the original data. - Pointer Receiver (
r *rect): The method gets a pointer to the struct. It can modify the original data.
Why use Methods?
- Encapsulation: Group logic together with the data it belongs to.
- Interfaces: To satisfy an interface, a type must implement specific methods.
- Clean Syntax: It often feels more natural to write
user.Save()thanSaveUser(user).
Important Rule
Go automatically handles conversion between values and pointers for method calls. If you call a pointer-receiver method on a value, Go will automatically pass the address (&).