×

go · level 2 · unit 2 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.