Go · Chapter 8 of 26

Pointers

By the end of this chapter you can take a value's address with &, reach the value through a pointer with *, write methods with pointer receivers that really change their struct, change a struct inside a slice, handle a nil pointer before it panics, and say when a pointer is the wrong choice. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: The language
  • 4 tasks
  • Go
  • In the all labs plan

The first 2 chapters of Go are free. This one comes with the all labs plan.

Why you need this

Every BijliGo driver pays from a prepaid wallet. When a session ends, the cost comes out of the wallet; when Pooja refunds one of Wednesday's 109 failed sessions, the money goes back in. Chapter 7 ended with a rule: passing a struct to a function, or calling a method with a value receiver, hands over a copy. A Debit method with a value receiver would take ₹347.70 out of a copy of the wallet and throw the copy away. The driver charges for free, and nobody sees an error.

Returning the changed struct, as you did in chapter 7, works for a bill you build once. It does not work for something many parts of the program share and change: a wallet, the slice of 1,180 chargers on Tenzin's dashboard, the day's counters. For those, the function needs to know where the value lives, so it changes the one value everybody sees. That "where" is a pointer.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    wallet.go: a wallet that really changes

    Write the two methods of Wallet (fields Driver and BalancePaise), both with pointer receivers as given, so they change the wallet they are called on.

    Credit(paise int) adds paise to BalancePaise. Debit(paise int) error takes paise away and returns nil.

    For Wallet{Driver: "D10005", BalancePaise: 172000}: Credit(5000) leaves 177000, then Debit(77000) returns nil and leaves 100000. Debit(100001) then returns an error for which errors.Is(err, ErrLowBalance) is true (return ErrLowBalance, or wrap it with %w), and the balance stays 100000. Debit(100000) returns nil and leaves 0. The Check also calls Credit(500) through a *Wallet of 131500 and expects 132000.

  2. Task 2

    faulted.go: find a charger and mark it faulted

    FindCharger(chargers []bijli.Charger, id string) *bijli.Charger returns a pointer to the charger with that ID inside the slice itself, so that a change made through the pointer changes the slice, or nil when no charger has that ID.

    MarkFaulted(chargers []bijli.Charger, id string) bool sets that charger's Status to "faulted" in the slice and returns true, or returns false and changes nothing when there is no such charger.

    The Check uses bijli.Chargers(): FindCharger(chargers, "C1110") must return the address of chargers[109], FindCharger(chargers, "C9999") nil; after MarkFaulted(chargers, "C1110"), chargers[109].Status is "faulted", and MarkFaulted(chargers, "C9999") returns false and changes no charger.

  3. Task 3

    discount.go: a discount that may not be there

    DiscountFor(d bijli.Driver) *Discount returns a new Discount (fields Fleet and Percent) for a driver in a fleet: 15 percent for NammaRide Autos, 10 for QuickDrop Deliveries, 12 for MetroCabs, with Fleet set to the driver's fleet. For a driver with no fleet (Fleet is "") it returns nil.

    (d Discount) Apply(paise int) int returns paise less Percent percent of paise, the discount being a whole number of paise (the fraction dropped): 10000 with 15 percent is 8500, 4289 with 10 percent is 3861, 4289 with 12 percent is 3775. On a nil Discount, Apply returns paise unchanged instead of panicking.

    The Check uses drivers D10016 (NammaRide Autos), D10014 (QuickDrop Deliveries), D10005 (MetroCabs) and D10010 (no fleet), and calls Apply on nil.

  4. Task 4 · interview question

    Interview: stats.go, the stats that stayed at zero

    ChargerStats (fields Charger, Sessions and EnergyWh) counts one charger's day: Add(wh int) counts one session of wh watt-hours, and StatsFor(id string, sessions []bijli.Session) ChargerStats adds every session whose Charger is id. Tenzin's version returns 0 sessions and 0 Wh for every charger. Fix it.

    The Check calls Add(1500) and Add(2500) on a ChargerStats of its own and expects 2 sessions and 4000 Wh in it. With bijli.Sessions(): StatsFor("C1600") is 4 sessions and 66260 Wh, StatsFor("C1777") 3 and 63075, StatsFor("C1126") 0 and 0, each with Charger set to the id.

    Joseph will ask: why did Add change nothing, and how do you choose between a value and a pointer receiver?

What you will learn

  • & and \*: the address of a value, and the value at an address.
  • **\*T**: the type "pointer to T", and Go's automatic p.Field.
  • Pointer receivers: func (w *Wallet) Debit(...), a method that changes its struct.
  • nil: a pointer to nothing, and the panic it causes.
  • new: a zero value, and a pointer to it.
  • The range copy: changing elements of a slice in a loop.
  • When not to use a pointer.

More in The language

Build "Pointers" yourself

BijliGo, a Bengaluru EV charging network, drops chargers at the evening peak. You rewrite its backend in Go. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Go are free. This one comes with the all labs plan.