Changing a value through its address
Every variable lives somewhere in the computer's memory, and that place has a number called its address. A pointer is a value that holds an address. With a pointer, you can reach a variable and change it from somewhere else in the program.
package main
import "fmt"
func main() {
x := 10
p := &x
fmt.Println(*p)
*p = 20
fmt.Println(x)
}
Output:
10
20
Two new symbols do the work:
| Code | Meaning |
|---|---|
&x | the address of x |
*p | the variable that p points to |
p := &x makes p point to x. The type of p is *int, which you read as "pointer to int". *p = 20 does not change p. It changes the variable p points to, and that is x.
Why pointers are needed
When you pass a value to a function, the function gets a copy. Changing the copy does not change the caller's variable. A pointer parameter fixes that:
package main
import "fmt"
func double(n int) {
n = n * 2
}
func doubleAt(n *int) {
*n = *n * 2
}
func main() {
x := 5
double(x)
fmt.Println(x)
doubleAt(&x)
fmt.Println(x)
}
Output:
5
10
double changed its own copy, so x stayed 5. doubleAt got the address of x, so it changed x itself.
You have used this since the Reading Input lesson. fmt.Scan(&n) gives Scan the address of n, so Scan can put the number it reads into n. If you forget the &, Scan gets only a copy, and n stays 0. Here the input is 7:
var n int
fmt.Scan(n)
fmt.Println(n)
Output:
0
Pointer receivers
The same copying happens with methods. A method with a value receiver like (c Counter) gets a copy of the struct, so this Add method changes nothing:
package main
import "fmt"
type Counter struct {
Count int
}
func (c Counter) Add() {
c.Count++
}
func main() {
c := Counter{}
c.Add()
c.Add()
fmt.Println(c.Count)
}
Output:
0
Go does not warn you about this bug. The fix is a pointer receiver: write *Counter instead of Counter.
package main
import "fmt"
type Counter struct {
Count int
}
func (c *Counter) Add() {
c.Count++
}
func main() {
c := Counter{}
c.Add()
c.Add()
fmt.Println(c.Count)
}
Output:
2
You still call c.Add(). Go sees that Add needs a pointer and passes &c for you. Inside the method, c.Count follows the pointer by itself, so you do not have to write (*c).Count.
A simple rule: if a method must change the struct, give it a pointer receiver.
The nil pointer
A pointer that points to nothing has the value nil. This is the zero value of every pointer type. Reading through a nil pointer crashes the program:
package main
import "fmt"
type Counter struct {
Count int
}
func main() {
var p *Counter
fmt.Println(p == nil)
fmt.Println(p.Count)
}
Output:
true
panic: runtime error: invalid memory address or nil pointer dereference
To dereference a pointer means to follow it to the value. When a pointer might be nil, check it with p == nil before you use it.
In the exercise, give the two methods of Order pointer receivers so they change the original order, and finish AddAttempt.