Go · Chapter 7 of 26
Structs and methods
By the end of this chapter you can make your own types with struct, build values of them with named fields, give them methods, print them with %v and %+v, compare them with ==, build one type out of another by embedding, and know that passing a struct to a function hands it a copy. 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 checks every bill BijliGo sends. A bill is not one number: it is a session id, the energy cost, an idle fee for a car that stayed plugged in after charging, and sometimes a discount. With what you know so far, that is four loose variables, and every function that works on a bill takes four parameters. Three of them are ints in paise, so a call that passes the idle fee where the discount belongs compiles without a word, and a driver is charged ₹10 instead of being given ₹10 off. Nandini wants a summary of each of the 240 stations at the end of the day: six numbers a station, 1,440 loose variables.
You have already used values that hold several named fields: bijli.Session has s.EnergyWh and s.CostPaise. Those are structs, and the bijli package made them. In this chapter you make your own, and give them methods, so a bill can work out its own total.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
bill.go: a bill as a struct
The Bill struct in bill.go has the fields Session (a string), EnergyPaise, IdleFeePaise and DiscountPaise (ints). Write its two methods, both with value receivers as given.
Total() int is the energy plus the idle fee less the discount, in paise, and never less than 0: for Bill{Session: "S901288", EnergyPaise: 31452, IdleFeePaise: 600, DiscountPaise: 1000} it is 31052, and for Bill{Session: "S901061", EnergyPaise: 5083, DiscountPaise: 6000} it is 0.
Receipt() string is the bill on one line: the session, a colon, then energy + idle fee - discount = total, each amount as ₹, the rupees, a point and the paise as two digits. For the two bills above:
S901288: ₹314.52 + ₹6.00 - ₹10.00 = ₹310.52
S901061: ₹50.83 + ₹0.00 - ₹60.00 = ₹0.00
The Check also tries Bill{Session: "S903327", EnergyPaise: 501, IdleFeePaise: 5}, whose receipt is S903327: ₹5.01 + ₹0.05 - ₹0.00 = ₹5.06.
- Task 2
charge.go: a session in your own type
You cannot add methods to bijli.Session, which belongs to another package, so copy what billing needs into your own type. The Charge struct in charge.go has the fields ID, Charger (strings), EnergyWh and PaisePerKWh (ints).
NewCharge(s bijli.Session) Charge returns a Charge with those four fields copied from the session's ID, Charger, EnergyWh and PaisePerKWh.
Cost() int is EnergyWh times PaisePerKWh divided by 1000, rounded to the nearest paisa (half a paisa rounds up), with ints only: for S901288 (charger C1725, 22466 Wh at 1400 paise a kWh) it is 31452. The Check compares Cost() with CostPaise for all 3,600 sessions of bijli.Sessions().
KWh() float64 is the energy in kWh: 22.466 for S901288.
- Task 3
station.go: a station's day in one struct
Summarize(st bijli.Station, sessions []bijli.Session) StationSummary fills in a StationSummary: ID and Name from the station, Chargers as the number of the station's chargers (its Chargers list), and Sessions, EnergyWh and RevenuePaise as the count of the sessions whose Station is st.ID and the sum of their EnergyWh and CostPaise. Count every one of them, failed sessions too.
AvgCostPaise() int is RevenuePaise divided by Sessions, a whole number (the remainder dropped).
With bijli.Sessions(): ST012 Koramangala Tech Park has 4 chargers, 15 sessions, 252467 Wh and 480356 paise, an average of 32023; ST050 Marathahalli Apartments has 6 chargers, 21 sessions, 145608 Wh and 190166 paise. With an empty list of sessions, Summarize(ST012) has ID, Name and Chargers and zero counts, and AvgCostPaise() returns 0 instead of panicking.
- Task 4 · interview question
Interview: idle.go, the idle fee that vanished
AddIdleFee(b Bill, minutes int) Bill adds the idle fee for a car that stayed plugged in after charging: the first 10 minutes are free, then 100 paise a minute, added to IdleFeePaise. Tenzin's version always returns the bill without the fee. Fix it.
For a bill with IdleFeePaise 0: 25 minutes gives IdleFeePaise 1500; 10 minutes or fewer (the Check tries 10 and 4) gives 0. A bill with IdleFeePaise 300 and 25 minutes gives 1800. The other fields stay as they were, and the bill passed in must not change: return the new one.
Joseph will ask: when you pass a Bill to a function, what does the function get? How does a change come back?
What you will learn
- struct: a type made of named fields, each with its own type.
- Struct literals: Plug{Charger: "C1002", PowerKW: 60}, and the zero value of the fields you leave out.
- %v and %+v: printing a struct, with and without its field names.
- Methods: functions with a receiver, called as p.Label().
- A copy: assigning or passing a struct copies every field.
- ==: comparing two structs field by field.
- Embedding and NewX constructors.
More in The language
Build "Structs and methods" 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.