Lesson 2 · Unit 05
Pointers and methods
Change a value through a pointer, and attach functions to your types.
What you practise
&and*, changing a value through a pointer,nil, methods, value receivers against pointer receivers
Try a question from this lesson
Pick one
A function gets a copy of a struct, so it cannot change yours. This one is handed &c instead: not a copy, but where c lives. What prints?
type Counter struct {
N int
}
func bump(c *Counter) {
c.N = c.N + 1
}
c := Counter{N: 5}
bump(&c)
bump(&c)
fmt.Println(c.N)Correct answer
7
Why
&c is a pointer: it tells bump where the counter is. Both calls change that one counter, so 5 becomes 6, then 7. With a plain Counter parameter each call would change a copy and you would still see 5.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Pointers
A pointer holds the place where a value lives.
&n gives a pointer to n. Its type is *int: "pointer to an int". *p follows the pointer to the value at the other end, to read it or to change it.
Two names for one value: change it through the pointer, and the original has changed.
n := 10
p := &n // p points at n
*p = 20 // change n through p
fmt.Println(n, *p) // 20 20Concept
Methods
A method is a function that belongs to a type. Between func and the name goes the receiver: the value the method works on.
You call a method with a dot, like a field with brackets: r.Area(). Inside, the receiver is an ordinary variable.
Methods keep the code for a type next to the type, and r.Area() reads better than area(r).
type Rect struct {
W int
H int
}
func (r Rect) Area() int {
return r.W * r.H
}
r := Rect{W: 3, H: 4}
fmt.Println(r.Area()) // 12Concept
Pointer receivers
To let a method change its value, make the receiver a pointer: (c *Counter).
You do not write & or * yourself here. c.Inc() hands over the address for you, and c.N follows the pointer for you.
Rule of thumb: a method that changes the value takes a pointer receiver. A method that only reads may take a plain one.
type Counter struct {
N int
}
func (c *Counter) Inc() {
c.N++ // the caller's counter
}
c := Counter{}
c.Inc()
c.Inc()
fmt.Println(c.N) // 29 more exercises in the app
- 3× type the answer
- 2× fill the blanks
- 2× multiple choice
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.