Explain it simply
Explain it simply
A method is simply a function that is tied to a type. If a Rectangle struct has a Width and a Height, you attach an Area() method so you can ask the rectangle itself "what is your area?". Instead of calling area(rect), you call rect.Area().
Go has no classes. Keeping data in a struct (or another named type) and attaching behavior with methods is Go's object-style approach. The (r Rectangle) written in parentheses before the function name is called the receiver, and it says which type the method belongs to.
Problem → Why → Solution
The problem: the method runs but nothing changes
You write a Counter type to count website visits and call its Inc() method three times. There is no compile error and no panic, yet printing the counter shows 0. The receiver type decides which piece of data a method actually works on.
type Counter struct {
Count int
}
func (c Counter) Inc() { // value receiver: c is a copy
c.Count++
}
func main() {
var visits Counter
visits.Inc()
visits.Inc()
visits.Inc()
fmt.Println(visits.Count) // prints 0, not 3
}Why does it stay at 0?
Go passes every argument by copying it, and the receiver is just another argument. With a value receiver like (c Counter), the c inside Inc() is a copy of visits, so c.Count++ increments the copy, which disappears when the method returns. Switch to a pointer receiver, (c *Counter), and the method gets the address of visits itself, so the program prints 3.
Core concept: the receiver is the method's first parameter
func (r Rectangle) Area() int is essentially a function that takes a Rectangle as r; calling rect.Area() passes rect in as r. A method must be declared in the same package as its type. That is why you cannot add a method to int or to time.Duration from another package; you first declare your own named type such as type Celsius float64. Methods are not limited to structs.
There are two kinds of receiver. A value receiver (r T) hands the method a copy on every call, which suits read-only work and small types. A pointer receiver (r *T) hands over the address of the original, so the method can change fields and large structs are not copied. Structs holding fields that must not be copied, such as a sync.Mutex, also need pointer receivers.
Go helps at the call site. If visits is an addressable variable, visits.Inc() is rewritten as (&visits).Inc(), and calling a value-receiver method through a pointer p becomes (*p).Area(). So callers rarely have to write & or * themselves.
A method set is the list of methods a type has. The method set of T contains only the value-receiver methods, while the method set of *T contains both the value-receiver and the pointer-receiver methods. This rule matters in the next lesson on interfaces: if a type has pointer-receiver methods, only *T satisfies an interface that needs them. One last rule concerns names: a method starting with a capital letter, like Area, can be called from other packages, while one starting with a lowercase letter, like area, is visible only inside its own package.
| Receiver | What the method gets | Use it when |
|---|---|---|
| (r T) | A copy of the value | Read-only work on a small type |
| (r *T) | The address of the original | Fields change, the struct is big, or must not be copied |
- You call rect.Area()
- rect is passed in as receiver r
- (r T) gets a copy, (r *T) an address
- When it returns, a copy is discarded
If a method must change a field, its receiver must be a pointer.
General pattern
type TypeName struct {
Field FieldType
}
func (r TypeName) Read() ResultType { // value receiver: gets a copy
return r.Field
}
func (r *TypeName) Change(v FieldType) { // pointer receiver: edits original
r.Field = v
}The receiver, written as (name Type), goes between func and the method name. Receiver names are short, often the first letter of the type (not this or self), and should be the same on every method of a type.
Example: an Area() method on Rectangle
This example has a Rectangle struct and one value-receiver method, Area(). Area() only reads Width and Height and changes nothing, so a value receiver fits. In main(), notice how the method is called with a dot, just like a field.
package main
import "fmt"
type Rectangle struct {
Width int
Height int
}
func (r Rectangle) Area() int {
return r.Width * r.Height
}
func main() {
rect := Rectangle{Width: 10, Height: 5}
fmt.Println("area:", rect.Area())
}Code breakdown
- Type
type Rectangle struct {The named type the method attaches to. The method must live in the same package as this type.
- Receiver
func (r Rectangle) Area() int {(r Rectangle) is the receiver. Because it is a value receiver, r is a copy of the calling rectangle; Area starts with a capital letter, so it is exported.
- Body
return r.Width * r.HeightThe receiver's fields are read like any variable. Writing r.Width = 0 here would only change the copy.
- Value
rect := Rectangle{Width: 10, Height: 5}Builds a struct literal using field names.
- Call
fmt.Println("area:", rect.Area())rect.Area() passes rect in as r and returns 10 * 5 = 50, so the program prints "area: 50".
area: 50Value and pointer receivers side by side
In the program below one Counter has two methods. IncCopy() has a value receiver, so it cannot change anything, while Inc() has a pointer receiver and really increments c.Count. You do not write & when calling c.Inc(); because c is a variable, Go turns the call into (&c).Inc().
package main
import "fmt"
type Counter struct {
Count int
}
// Value receiver: works on a copy.
func (c Counter) IncCopy() {
c.Count++
}
// Pointer receiver: works on the caller's Counter.
func (c *Counter) Inc() {
c.Count++
}
func main() {
var c Counter
c.IncCopy()
fmt.Println("after IncCopy:", c.Count)
c.Inc() // Go rewrites this as (&c).Inc()
c.Inc()
fmt.Println("after Inc x2:", c.Count)
}This program prints "after IncCopy: 0" and then "after Inc x2: 2".
Methods on non-struct types, and method values
A named type such as type Celsius float64 can carry conversion methods like Fahrenheit(). If it has a String() string method, the fmt package uses it automatically when printing the value (that is the fmt.Stringer interface at work). Writing t.Fahrenheit without parentheses gives a method value: a function with a copy of the receiver bound at that moment, so changing t later does not affect it.
package main
import "fmt"
type Celsius float64
func (c Celsius) Fahrenheit() float64 {
return float64(c)*9/5 + 32
}
func (c Celsius) String() string {
return fmt.Sprintf("%.1f°C", float64(c))
}
func main() {
t := Celsius(36.6)
fmt.Printf("%v = %.1f°F\n", t, t.Fahrenheit())
toF := t.Fahrenheit // method value: binds a copy of t now
t = 100
fmt.Printf("bound: %.1f, current: %.1f\n", toF(), t.Fahrenheit())
}The output is "36.6°C = 97.9°F" followed by "bound: 97.9, current: 212.0". toF remembers the copy taken before t = 100, so it still returns 97.9.
In real projects
Where this shows up in real projects
The standard library is full of methods. time.Time has value-receiver methods such as Add(), Before() and Format() that return a new value instead of changing the existing one. strings.Builder and bytes.Buffer use pointer-receiver methods such as WriteString() that modify their internal buffer in place. These are exactly the two styles you choose between in your own code.
In a web service, a struct such as OrderService usually holds its database connection and logger as fields and does its work through methods like Create() and Cancel(). Keeping dependencies in the struct instead of in global variables means a test can plug in a fake database. Domain types benefit too: methods like Order.Total() or User.IsAdmin() keep business rules in one place instead of scattering them across HTTP handlers. Many teams also follow the convention that once a type has one pointer-receiver method, all its methods use pointer receivers for consistency.
Common mistakes
Common mistakes
1. Using a value receiver for a method that changes fields
func (a Account) Deposit(n int) { a.balance += n } compiles and reports nothing, but the balance never grows. When a method name describes a change, such as Set, Add, Reset or Deposit, check first that its receiver is *Account.
2. Calling a pointer method on a map element
Writing counters["home"].Inc() fails with "cannot call pointer method Inc on Counter". Map elements are not addressable, so Go cannot insert the & for you. Use map[string]*Counter, or copy the value out, change it and store it back.
3. Starting a method that other packages need with a lowercase letter
func (r Rectangle) area() int works fine inside its package, but another package calling rect.area() gets "rect.area undefined". When designing a library or API, decide deliberately which methods are public by choosing the capital or lowercase first letter.
Best practices
Best practices
- Use a short receiver name such as r, c or a, and keep it identical across all methods of a type.
- Avoid mixing value and pointer receivers on one type; picking one style makes its method set predictable.
- Put methods next to the type whose data they use, and keep helpers that do not need that data as plain functions.
Mini challenge
Mini challenge: a bank account
Write an Account type with methods for depositing and withdrawing money. Decide yourself which methods need a pointer receiver.
- Deposit(amount int): does nothing for zero or negative amounts
- Withdraw(amount int) bool: returns false and leaves the balance alone when the amount exceeds it
- Balance() int and String() string use value receivers
- fmt.Println(acc) prints the form "Aye: 3000 MMK"
package main
import "fmt"
type Account struct {
// TODO: Owner (exported) and balance (unexported) fields
}
// TODO: Deposit — which receiver lets it change the balance?
// TODO: Withdraw(amount int) bool
// TODO: Balance() int and String() string
func main() {
// TODO: deposit 5000, try a negative deposit, withdraw 2000 then 9000,
// print the balance and the account itself
fmt.Println("todo")
}Expected: The program prints: withdraw 2000: true withdraw 9000: false balance: 3000 Aye: 3000 MMK
Show hint
Deposit and Withdraw change the balance, so they need an (a *Account) receiver. Because acc is a variable, acc.Deposit(5000) works without writing &. Write String() with a value receiver so fmt.Println(acc) finds it.
Show solution
package main
import "fmt"
type Account struct {
Owner string
balance int
}
func (a *Account) Deposit(amount int) {
if amount <= 0 {
return
}
a.balance += amount
}
func (a *Account) Withdraw(amount int) bool {
if amount <= 0 || amount > a.balance {
return false
}
a.balance -= amount
return true
}
func (a Account) Balance() int {
return a.balance
}
func (a Account) String() string {
return fmt.Sprintf("%s: %d MMK", a.Owner, a.balance)
}
func main() {
acc := Account{Owner: "Aye"}
acc.Deposit(5000)
acc.Deposit(-100)
fmt.Println("withdraw 2000:", acc.Withdraw(2000))
fmt.Println("withdraw 9000:", acc.Withdraw(9000))
fmt.Println("balance:", acc.Balance())
fmt.Println(acc)
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A method is a function with a receiver, declared in the same package as its type.
- A value receiver (r T) works on a copy; a pointer receiver (r *T) changes the original.
- On a variable, Go inserts & and * for you, but not on non-addressable values such as map elements.
- The method set of T has only value-receiver methods; the method set of *T has both kinds.
- Only methods whose names start with a capital letter can be called from other packages.
A Tour of Go — Go