Introduction
In the last lesson you grouped data into structs. A struct becomes much more useful when it also has behaviour: a bank account that can deposit and withdraw, a counter that can count up. In Go you give a type behaviour with methods. To let a method change the value it works on, you need to know about pointers. Pointers have a reputation for being hard, but in Go they are simple and safe: there is no pointer arithmetic, and the language tidies most things up for you.
How it works
A method is a function with a receiver, written between func and the name. The receiver says which type the method belongs to:
type Rect struct {
W, H int
}
func (r Rect) Area() int {
return r.W * r.H
}
You call it with a dot: r.Area(). This receiver is a value receiver: the method gets a copy of the struct, so it cannot change the original.
To understand how to change the original, look at pointers. Every variable lives at an address in memory. &x gives the address of x, and its type is *int if x is an int. Writing *p follows the pointer and gives the value it points to, and you can assign to it: *p = 5 changes the original. A pointer that points at nothing is nil; following a nil pointer stops the program.
x := 1
p := &x
*p = 2
Now x is 2. Go copies arguments, so a function that receives an int cannot change the caller's int, but one that receives a *int can. The same rule applies to methods. A pointer receiver gets the address of the value, so it can change it:
func (c *Counter) Inc() {
c.n++
}
Go lets you write c.Inc() on a plain variable c, and takes the address for you. Use a pointer receiver when the method changes the value, or when the struct is big and you do not want to copy it. Keep one kind per type to avoid confusion.
It is common to write a constructor, a normal function named NewSomething that sets up and returns a pointer: func NewAccount(owner string) *Account. Returning the address of a local variable is safe in Go; the value lives as long as it is used.
If a type has a method String() string, then fmt.Println uses it to print the value. This is a great way to give your types a readable form. Pointers are also what you use to build linked structures such as lists and trees, where a node holds a pointer to the next node.
Example
package main
import "fmt"
type Counter struct {
n int
}
func (c *Counter) Inc() {
c.n++
}
func (c Counter) Value() int {
return c.n
}
func double(p *int) {
*p = *p * 2
}
func triple(x int) {
x = x * 3
}
type Account struct {
Owner string
Balance int
}
func NewAccount(owner string) *Account {
return &Account{Owner: owner}
}
func (a *Account) Deposit(x int) {
a.Balance += x
}
func (a *Account) Withdraw(x int) bool {
if x > a.Balance {
return false
}
a.Balance -= x
return true
}
func (a *Account) String() string {
return fmt.Sprintf("%s has %d", a.Owner, a.Balance)
}
func main() {
var c Counter
c.Inc()
c.Inc()
fmt.Println(c.Value())
x := 10
p := &x
*p = 20
fmt.Println(x)
double(&x)
triple(x)
fmt.Println(x)
acct := NewAccount("Ada")
acct.Deposit(100)
fmt.Println(acct.Withdraw(30), acct.Withdraw(500))
fmt.Println(acct)
}Line by line
Counterhas a pointer receiver onInc, so it can change the count, and a value receiver onValue, which only reads it.c.Inc()works on the variablec; Go passes its address automatically.p := &xstores the address ofx, and*p = 20changesxitself.doublereceives a pointer and changes the caller's number;triplereceives a copy and changes nothing.NewAccountis a constructor that returns a pointer, andDepositandWithdrawchange the balance.StringonAccountis used byPrintlnto print the account.
Expected result
2
20
40
true false
Ada has 70
In the real world
Nearly all Go code that models something with state uses pointer receivers: a server, a database connection, a shopping cart. The standard library does the same, for example a strings.Builder is used through a pointer. Pointers also make programs faster, since passing a pointer copies eight bytes instead of a whole large struct. Because Go has garbage collection, you never free memory yourself.
Common mistakes
- Using a value receiver for a method that changes the struct. The change is lost.
- Following a nil pointer, which stops the program. Check for
nilwhen it is possible. - Mixing pointer and value receivers on one type.
- Forgetting the & when a function needs an address.
- Thinking that range copies are the original, as with structs in a slice.
Best practices
- Use a pointer receiver when a method changes the receiver, and give a type either all or none.
- Write
NewXconstructors that make valid values. - Add a
Stringmethod to types that you print often.
Summary
A method is a function with a receiver and is called with a dot. &x gives an address and *p follows a pointer. A value receiver works on a copy; a pointer receiver can change the original. Constructors return pointers, and a String method controls how fmt prints a value.
Quick check
Key takeaways
- A method is a function with a receiver: func (a *Account) Deposit(x int).
- &x gives the address of x and *p follows the pointer; a pointer lets a function change the original.
- Use a pointer receiver when a method changes the value or the struct is large.
Practice problems for this lesson
Was this lesson clear?
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.