Go · Chapter 9 of 26
Interfaces
By the end of this chapter you can describe a behaviour with an interface type, let any type satisfy it just by having the methods, make fmt print your types your way with String, write error types that carry data and find them with errors.As, look inside an any with a type assertion or a type switch, and explain why an interface holding a nil pointer is not nil. 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
Pooja has decided that evening sessions cost more. From 6 pm to 10 pm, when 2,128 of Wednesday's 3,600 sessions started, a kWh will cost a little extra; the rest of the day stays flat. Next month there will be a fleet rule, and after that something else. The billing code should not care which rule a charger uses. It needs one thing from every rule: a price for some energy.
With what you know so far, you could write a function for each rule and a switch that picks one, and add a case to that switch in every place that prices a session, every time Pooja adds a rule. Miss one place and a driver pays the wrong amount. What billing wants is to say "anything that can price energy" as a type, and let each rule be that type on its own. That is an interface.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
price.go: two price rules behind one interface
PriceRule is an interface with one method, Price(wh int) int. Give FlatRate and PeakRate a Price method each, so both satisfy it, and write TotalPrice(rule PriceRule, whs []int) int, the sum of rule's price for each wh in whs (0 for none).
Every price is wh times the rate divided by 1000, rounded to the nearest paisa (half a paisa up). FlatRate always uses PaisePerKWh: FlatRate{PaisePerKWh: 2000}.Price(17385) is 34770, and FlatRate{PaisePerKWh: 1400}.Price(3064) is 4290. PeakRate uses PeakPaisePerKWh when Hour is 18, 19, 20 or 21 (6 pm to before 10 pm) and PaisePerKWh otherwise: PeakRate{PaisePerKWh: 2000, PeakPaisePerKWh: 2600, Hour: 19}.Price(17385) is 45201, and with Hour 9 or 22 it is 34770.
The Check also passes TotalPrice a price rule type of its own (the first 5 kWh free), so TotalPrice must call the rule's Price for each wh, whatever the rule is.
- Task 2
card.go: one line for anything on the dashboard
Charger embeds a bijli.Charger. Give it a String() string method that returns the id, the kind, the power as %v prints it, the station and the status, exactly like this for C1051 and C1001:
C1051: AC7, 7.4 kW at ST009, available
C1001: DC60, 60 kW at ST001, available
fmt then prints a Charger that way too (the Check uses fmt.Sprint and %v).
Describe(v any) string returns one line for any value, by its type: for a Charger, its String(); for a bijli.Station, the id, the name and the number of chargers (ST009 Sarjapur Road Metro, 4 chargers); for a bijli.Session, the id, the charger and the energy (S900436 on C1051, 5333 Wh); for any other type, unknown and the type as %T prints it (unknown int, unknown string, and for a plain bijli.Charger, unknown bijli.Charger).
- Task 3
starterr.go: an error that carries its charger
ChargerError has the fields Charger and Status. Its Error() method (a pointer receiver, as given) returns charger, the id, is, and the status: charger C1023 is offline.
CanStart(chargers []bijli.Charger, id string) error looks the id up in the chargers it is given. For a charger whose Status is available it returns nil. For one that is offline or faulted it returns a ChargerError with Charger and Status set (returned as it is, or wrapped with %w), so that errors.As with a ChargerError target finds it and err.Error() contains its sentence. For an id that is not in the list it returns an error for which errors.Is(err, bijli.ErrUnknownCharger) is true, and which is not a ChargerError.
The Check uses bijli.Chargers(): C1051 is available, C1023 offline, C1019 faulted, and C9999 does not exist. It also marks C1051 faulted in its own list and expects a *ChargerError for it.
- Task 4 · interview question
Interview: reading.go, the error that was never nil
CheckReading(r bijli.Reading) error rejects a meter reading that cannot be true: a negative MeterWh (Problem "negative meter") or a PowerW above 60000 (Problem "power above 60 kW"), each as a *ReadingError that errors.As finds. Tenzin's version rejects every reading, good ones too. Fix it.
For every one of the 1,263 readings of bijli.Readings(), all good, CheckReading must return nil, so that err == nil is true. The Check also tries a reading with MeterWh -5 and one with PowerW 75000.
Joseph will ask: the function returned a nil *ReadingError as an error, and err != nil was true. Why?
What you will learn
- interface types: a set of methods, and any type that has them satisfies it, with no implements.
- Small interfaces: one or two methods, like Go's own.
- fmt.Stringer: a String method changes how fmt prints your type.
- error is an interface: your own error types, and errors.As.
- any, type assertions with ok, and type switches.
- The nil interface that is not nil.
More in The language
Build "Interfaces" 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.