Course › Week 2 · Methods, interfaces, errors, tests › Day 1 · lesson 8 of 42 · 20 min reading + 60–75 min practice
Pointers and methods
Change a value through a pointer, and give a type methods, with a value or a pointer receiver.
Go passes everything by copying it: a struct handed to a function is a new copy of every field. When the function must change the caller’s value, you hand it the value’s address instead, a pointer. PHP does this for you with objects, invisibly; Go makes you say it.
Today: copies, pointers, the panic a nil pointer causes, methods, the two kinds of receiver, and why a slice passed to a function behaves half like a pointer.
Pointers
1. A function gets a copy
addNight changes its parameter, and the caller’s booking stays the same:
package main
import "fmt"
type Booking struct {
Guest string
Nights int
}
func addNight(b Booking) {
b.Nights++
fmt.Println("inside: ", b.Nights)
}
func main() {
booking := Booking{Guest: "Astrid", Nights: 3}
addNight(booking)
fmt.Println("outside:", booking.Nights)
}
inside: 4
outside: 3The same copy as range in the structs lesson. It is a feature: a function that receives a value cannot change your value behind your back.
2. & takes the address, *T is a pointer
&booking is the address of booking. Its type is *Booking, “pointer to Booking”. A function that takes a *Booking works on the caller’s value.
package main
import "fmt"
type Booking struct {
Guest string
Nights int
}
func addNight(b *Booking) {
b.Nights++
}
func main() {
booking := Booking{Guest: "Astrid", Nights: 3}
addNight(&booking)
addNight(&booking)
fmt.Println(booking.Nights)
}
5Inside addNight, b.Nights reads the field through the pointer: Go follows it for you. The signature now tells every reader that this function changes its argument, and the & at the call says the same thing where it happens.
3. * reads and writes through a pointer
For a pointer to anything other than a struct, *p is the value it points to.
package main
import "fmt"
func main() {
retries := 0
p := &retries
*p = *p + 1
fmt.Println(retries, *p)
fmt.Printf("%T\n", p)
}
1 1
*intp holds the address of retries, so *p = … changes retries itself. * has two jobs: in a type (*int) it means “pointer to”, in an expression (*p) it means “the value at”. There is no pointer arithmetic in Go: you cannot add 1 to an address.
4. A nil pointer panics
The zero value of a pointer is nil: it points nowhere. Reading through it crashes the program:
package main
import "fmt"
type Booking struct {
Guest string
Nights int
}
func main() {
var booking *Booking
fmt.Println(booking.Nights)
}
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x10 pc=0x499e56]
goroutine 1 [running]:
main.main()
/tmp/go-playbook/hello/main.go:13 +0x16
exit status 2“nil pointer dereference” is the Go version of PHP’s “Attempt to read property on null”. The compiler does not catch it, and here neither does staticcheck.
The habit: a function that returns a pointer either returns a usable one or returns an error, never nil with a nil error. Then callers check the error, as always, and never have to check the pointer.
Methods
5. A method with a value receiver
A method is a function with a receiver, written in parentheses before the name. It belongs to the receiver’s type and is called with a dot.
package main
import "fmt"
type Booking struct {
Guest string
Nights int
NightlyCents int
}
func (b Booking) TotalCents() int {
return b.Nights * b.NightlyCents
}
func main() {
booking := Booking{Guest: "Astrid", Nights: 3, NightlyCents: 12950}
fmt.Println(booking.TotalCents())
}
38850There is no class and no $this. The receiver has a name you choose, by convention one or two letters of the type: b for Booking. Methods are written outside the struct, usually right below it.
With (b Booking) the method gets a copy, like any parameter. That is right for a method that only reads.
6. A method with a pointer receiver
A method that changes its value takes a pointer receiver, (b *Booking).
package main
import (
"errors"
"fmt"
)
const maxNights = 28
type Booking struct {
Guest string
Nights int
}
func (b *Booking) Extend(nights int) error {
if b.Nights+nights > maxNights {
return errors.New("a stay cannot be longer than 28 nights")
}
b.Nights += nights
return nil
}
func main() {
booking := Booking{Guest: "Astrid", Nights: 3}
if err := booking.Extend(2); err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("nights:", booking.Nights)
if err := booking.Extend(30); err != nil {
fmt.Println("error:", err)
}
fmt.Println("nights:", booking.Nights)
}
nights: 5
error: a stay cannot be longer than 28 nights
nights: 5booking.Extend(2) works even though booking is a plain Booking, not a pointer: Go takes the address for you, (&booking).Extend(2), because booking is a variable it can point to.
The method checks its rule and returns an error instead of changing the booking into something invalid. A struct whose fields are only changed through such methods keeps its rules, like a PHP class with private properties and setters that validate.
7. Methods on a type that is not a struct
Any type you define can have methods, including the Level from the structs lesson.
package main
import "fmt"
type Level int
const (
Debug Level = iota
Info
Warning
Error
)
var levelNames = []string{"DEBUG", "INFO", "WARNING", "ERROR"}
func (l Level) Name() string {
if l < 0 || int(l) >= len(levelNames) {
return fmt.Sprintf("Level(%d)", int(l))
}
return levelNames[l]
}
func (l Level) IsSerious() bool {
return l >= Warning
}
func main() {
for _, l := range []Level{Info, Error, Level(9)} {
fmt.Println(l.Name(), l.IsSerious())
}
}
INFO false
ERROR true
Level(9) truefmt.Sprintf is Printf that returns the string instead of printing it, PHP’s sprintf. The range check makes Name safe for a Level that matches none of the constants, like Level(9): it never indexes past the end of the slice.
The receiver type must be defined in the same package as the method. You cannot add methods to int or string themselves, only to your own types made from them.
8. Which receiver to choose
Use a pointer receiver (b *Booking) when | A value receiver (b Booking) is fine when |
|---|---|
| the method changes the value | the method only reads |
| the struct is large, so copying it on every call costs something | the type is small: a number, a Level, a struct of a few fields |
| any other method of the type has a pointer receiver: keep them consistent | all methods of the type only read |
In practice most methods on structs that hold data have pointer receivers, and methods on small named types like Level have value receivers. The interfaces lesson shows the one place where the choice changes what compiles.
Slices and maps inside functions
9. Why a slice behaves half like a pointer
A slice value is small: a pointer to an array of elements, a length and a capacity. Passing a slice copies those three, so the function shares the elements but has its own length:
package main
import "fmt"
func discountAll(totals []int) {
for i := range totals {
totals[i] = totals[i] * 90 / 100
}
}
func addFee(totals []int) {
totals = append(totals, 4500)
fmt.Println("inside addFee:", totals)
}
func main() {
totals := []int{38850, 90650}
discountAll(totals)
fmt.Println("after discountAll:", totals)
addFee(totals)
fmt.Println("after addFee: ", totals)
}
after discountAll: [34965 81585]
inside addFee: [34965 81585 4500]
after addFee: [34965 81585]discountAll changes the shared elements, so the caller sees them. addFee appends to its own copy of the slice value; the caller’s totals still has length 2 and never sees the new element. Nothing warns about it: the code is valid, and the bug is in the design.
The rule: a function that changes a slice’s length returns the new slice, as append does: func addFee(totals []int) []int. A map is a pointer inside too: a function that adds a key to a map it received changes the caller’s map.
Coming from PHP
<?php
final class Booking
{
public function __construct(public string $guest, public int $nights) {}
public function extend(int $nights): void { $this->nights += $nights; }
}
function addNight(Booking $b): void { $b->nights++; } // changes the caller's object
function addFee(array $totals): void { $totals[] = 4500; } // a copy: the caller sees nothing
function addFeeByRef(array &$totals): void { $totals[] = 4500; }
A PHP object variable holds a handle, so every function you pass it to can change it, and nothing in the signature tells you. A PHP array is copied, unless the parameter has &. Go uses one rule for all types: everything is copied, and a pointer in the signature is the visible way to share.
Methods are the same idea as PHP methods, minus the class around them. A Go type has no constructor, no inheritance and no static; the next lesson shows what takes the place of implements.
PracticeA Tour of Go: pointers and methods, one small program
In A Tour of Go, do Pointers and Pointers to structs, then the methods pages from Methods to Choosing a value or pointer receiver.
Exercise: a guest list
Define type GuestList struct { Names []string; Max int } with two methods: Add(name string) error, which refuses an empty name, a name already on the list, and a full list, each with its own message; and Count() int. Choose each receiver on purpose. In main, add four names to a list with a maximum of 3, including one duplicate, and print every error and the final count.
Show the solution
package main
import (
"errors"
"fmt"
)
type GuestList struct {
Names []string
Max int
}
func (g *GuestList) Add(name string) error {
if name == "" {
return errors.New("a guest needs a name")
}
for _, existing := range g.Names {
if existing == name {
return fmt.Errorf("%s is already on the list", name)
}
}
if len(g.Names) >= g.Max {
return fmt.Errorf("the list is full at %d guests", g.Max)
}
g.Names = append(g.Names, name)
return nil
}
func (g *GuestList) Count() int {
return len(g.Names)
}
func main() {
list := GuestList{Max: 3}
for _, name := range []string{"Astrid", "Bjorn", "Astrid", "Clara", "Dagny"} {
if err := list.Add(name); err != nil {
fmt.Println("error:", err)
}
}
fmt.Println("guests:", list.Count(), list.Names)
}
error: Astrid is already on the list
error: the list is full at 3 guests
guests: 3 [Astrid Bjorn Clara]Add changes the list, so it needs a pointer receiver. Count only reads, but it uses a pointer receiver too, to keep the type consistent (section 8).
Remember
- A function that must change its argument takes a pointer, and the
&at the call shows it. - Methods that change their value have pointer receivers; keep all methods of a type on the same kind of receiver.
- A function that changes a slice’s length returns the new slice.
Tomorrow: interfaces, which a type satisfies just by having the right methods.