go · level 2 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A lets a method change the real struct.
A receiver is a kind of parameter, so it gets a copy too. A method with a , like func (a Account) Deposit(amount int), adds the money to a copy. The copy is thrown away when the method ends.
Add a star to make it a pointer receiver: func (a *Account) Deposit(amount int). Now a points at the real account, so the new balance sticks. You still write a.Balance with no star, because Go follows the pointer for you.
Calling looks the same: acc.Deposit(5). Go sees the pointer receiver and hands over &acc for you. A good habit: if one method of a type needs a pointer receiver, give all its methods one.
package main
import "fmt"
type Account struct {
Owner string
Balance int
}
func (a *Account) Deposit(amount int) {
a.Balance = a.Balance + amount
}
func (a *Account) Report() string {
return fmt.Sprintf("%v has £%v", a.Owner, a.Balance)
}
func main() {
acc := Account{Owner: "Priya", Balance: 20}
acc.Deposit(15)
acc.Deposit(5)
fmt.Println(acc.Report())
} Go can only add the & for you when the value lives in a box, like the variable acc.
guess first
Click, click. What does the counter say?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
type Counter struct {
Clicks int
}
func (c Counter) Click() {
c.Clicks++
}
func main() {
tally := Counter{}
tally.Click()
tally.Click()
fmt.Println(tally.Clicks)
}
your turn
Your turn. Fill the piggy bank for real.
Fill the first blank so Add changes the real piggy bank, not a copy. Then choose two whole numbers of coins above 0 to drop in.
output
press run to see what happens
fix it
Zip the hero never loses a life. Fix it!
output
press run to see what happens
- The program runs, but Zip still has 3 lives. Which
PlayerdoesLoseLifereally change? LoseLifehas a value receiver, so it takes a life from a copy ofhero.- Change (p Player) to (p *Player) on line 7, then run.
nailed it
your methods can change things now. :D
- A value receiver works on a copy.
- A pointer receiver, like
(a *Account), changes the real struct. - Go adds the
&for you when you call the method.
new words in your collection
- pointer receiver
- value receiver
This lesson isn’t saved. A free account remembers every lesson you finish.