Lab · Go Programming (backend and cloud)
Lab: electricity bills for a housing society
The brief
Sai Krupa Housing Society shares one billing program for its flats. You write the slab calculation with switch, a bill function that returns the charge, the total and an error, a variadic function for the society total, a closure that numbers receipts, and a deferred "finished" line.
Why it matters
Slab tariffs (electricity, water, income tax) are everywhere in Indian billing software, and they are a classic place for off-by-one bugs. Functions that return a value and an error, small closures and defer are the everyday tools of every Go codebase you will join.
Skills you practise
- switch with no value
- for and range
- multiple and named return values
- errors.New
- variadic functions
- closures
- defer
You need
- Go 1.22 or newer installed from go.dev/dl
- A module made with go mod init example.com/ebill (as in the module 1 lab)
What you will have at the end
main.go for the society's billing run: correct slab charges, an error for bad readings, numbered receipts and a society total of Rs 2160.
How it is marked (rubric, 100 points)
| Correct slab mathsRs 240, 550 and 1220 for 80, 150 and 260 units; bills include the fixed charge. | 35 |
|---|---|
| Errors the Go waybill returns an error for negative units and main checks it before using the result. | 20 |
| Functions used wellA variadic sum, a closure that keeps its own counter, and a deferred final line. | 30 |
| Readable codeClear names, gofmt and go vet clean, no repeated slab code. | 15 |
0/5 steps done
Step 1 of 5
Charge each slab at its own rate
energyCharge gives Rs 240 for 80 units, Rs 550 for 150 units and Rs 1220 for 260 units.
In a slab tariff, only the units inside a slab get that slab's rate. 150 units is 100 units at Rs 3 plus 50 units at Rs 5 = Rs 550, not 150 x 5. A switch with no value reads like a list of conditions, and Go stops at the first case that is true, so order the cases from the smallest limit up. Make a module (go mod init example.com/ebill), copy main.go in, and run it.
$ go run .Your notes: main.go
Write down each command you ran. It goes into your project summary.