go · level 2 · unit 2 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A says where a box lives, not what is inside.
When you hand a value to a function, Go hands over a copy. The function can change its copy as much as it likes, and your original box stays the same. Sometimes that is exactly what you do not want.
Every box lives at an , like a house number. &score gives that address, and a value holding an address is a pointer. Its type has a star: &score is an *int, a pointer to an int.
Put a star in front of a pointer to reach the box it points at, so *p = 10 changes the original. Remember fmt.Scan(&answer)? You handed Scan a pointer, so it could fill your box.
package main
import "fmt"
func addBonus(points *int) {
*points = *points + 10
}
func main() {
score := 5
addBonus(&score)
fmt.Println(score)
p := &score
*p = 100
fmt.Println(score)
} In a type, *int means pointer to an int, while in code *p means the box that p points at.
guess first
A copy or the real thing? Guess first.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func resetCopy(n int) {
n = 0
}
func resetReal(n *int) {
*n = 0
}
func main() {
a := 7
b := 7
resetCopy(a)
resetReal(&b)
fmt.Println(a, b)
}
your turn
Your turn. Level up the real player.
In the first blank, hand levelUp the address of the level box, so it can change the real thing. In the second, choose how many levels to jump.
output
press run to see what happens
fix it
The fuel tank never fills up. Can you fix it?
output
press run to see what happens
- Read the error. Which type does
fillUpwant, and what is it handed on line 8? fillUpwants an*int, the address of a box, but it is handed the number insidefuel.- Change fillUp(fuel) to fillUp(&fuel), then run.
nailed it
you can point at the real box. :D
- Functions get copies, so changing a copy changes nothing else.
&boxgives an address, and its type is a pointer like*int.*preaches the box that a pointer points at.
new words in your collection
- pointer
- address
This lesson isn’t saved. A free account remembers every lesson you finish.