Practice: write your first Go program
A short warm-up with no repo tests: a small program with a struct, a method, a map, a function with two return values, an error and a defer.
Objective
Build a small rate-limiter-flavoured Go program that combines the language features from lessons 1.4 to 1.7. This optional warm-up gives you a chance to use functions, structs, methods, interfaces, maps, control flow, and error handling together before moving on to the rate limiter exercises.
By the end:
- A
Countertracks how many times each user has been seen. - A
CountingGateimplements aGateinterface and allows users up to a configured limit. - Invalid input returns an error that the caller handles immediately.
- The program prints each decision and a summary in first-seen user order.
deferprintsdoneas the final line.
This exercise is optional. It does not block the week, is not part of the zomato-prep repository, and has no repository tests.
Deliverables
-
~/warmup/main.go: A standalone Go program withpackage maincontaining:- A
Counterstruct with amap[string]int. - A
NewCounterconstructor returning*Counter. - An
Addmethod that increments a user's count or returns an error. - A
Countmethod that returns the current count for a user. - A
Gateinterface with anAllowmethod. - A
CountingGatestruct with a limit and a counter. - An
Allowmethod that delegates counting toCounter.Add. - A
mainfunction that exercises the gate, handles errors, prints decisions, and displays the summary.
Required signatures:
go type Counter struct { counts map[string]int } func NewCounter() *Counter func (c *Counter) Add(user string) (int, error) func (c *Counter) Count(user string) int type Gate interface { Allow(user string) (bool, error) } type CountingGate struct { limit int counter *Counter } func (g *CountingGate) Allow(user string) (bool, error) - A
Requirements
Constraints
-
Work in a scratch folder outside the
zomato-preprepository. Create it and initialize a separate Go module:bash mkdir -p ~/warmup cd ~/warmup go mod init warmup -
Use only the Go standard library. You need
fmtfor output anderrorsfor constructing the empty-user error. -
Implement
Counterwith a map from user names to integer counts. Initialize the map inNewCounter. -
In
Counter.Add, return an error with the exact textempty userwhen the supplied user is an empty string. Otherwise increment the count and return the new value. -
Implement
Counter.Count(user string) intto read a user's count from the map. -
Declare
GatewithAllow(user string) (bool, error). -
Implement
CountingGatewith:limit intcounter *Counter
-
CountingGate.Allowmust callCounter.Add, pass any error back to its caller, and report whether the resulting count is less than or equal to the configured limit. -
In
main, create aCountingGatewith a limit of2. Store it in a variable whose declared type isGate, not*CountingGate. -
Process this exact input slice using
for range:go []string{"asha", "bo", "asha", "asha", "", "bo"} -
For each user:
- Print
<user>: allowedwhen the gate allows the request. - Print
<user>: rejectedwhen the gate rejects the request. - If
Allowreturns an error, printerror: empty userand usecontinueto skip the remaining processing for that input.
- Print
-
Keep a separate slice of first-seen users for the summary. Add a user to it only the first time that user appears. Do not rely on map iteration order.
-
Print the summary in first-seen order using
Counter.Countto retrieve the counts. -
Call
defer fmt.Println("done")near the beginning ofmain. -
Do not use global variables.
-
Check every returned error immediately in the caller.
-
Use pointer receivers for methods that mutate their receiver.
-
Format the file with
gofmt.
Acceptance criteria
-
Expected output: Running
go run .prints exactly these eight lines, in this order:asha: allowed bo: allowed asha: allowed asha: rejected error: empty user bo: allowed summary: asha=3 bo=2 done -
Interface usage: The gate is stored in a variable declared as
Gate, and the program callsAllowthrough that interface value. -
Error handling: The empty user produces
error: empty user. The error is checked and handled without terminating the program. -
Summary ordering: The summary always lists
ashabeforebo, based on first appearance rather than map iteration. -
Formatting and vetting:
go vet ./...reports no issues, andgofmt -l .prints nothing. -
Run locally: From the scratch folder, execute:
bash go run . go vet ./... gofmt -l .There is no
makecommand for this exercise because it has no repository test target and is deliberately completed outsidezomato-prep. The repository commandmake test W=...does not apply.
The reference solution passes every check for this exercise. Try the hints first; reading the answer before you have struggled with the problem teaches much less.
Go fundamentals
5 items
- 1.4Go basics: types, functions and defernot completed
- 1.5Structs, pointers, slices and mapsnot completed
- 1.6Methods and receiversnot completed
- 1.7Interfaces and Go errorsnot completed
- 1.8Practice: write your first Go programnot completed
Up next · Module 3 · 3 items · about 2 h 45 min
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
- The program runs with
go run .. - It defines a struct and a method on it.
- It stores and reads values in a map and uses the comma-ok form.
- It has a function that returns a value and an error, and the caller checks the error.
- It uses
deferto print a closing message.
Commands
mkdir -p /tmp/warmup && cd /tmp/warmup && go mod init warmupcd /tmp/warmup && go run .This exercise has no Go test. The commands above are the check: when each one shows what the list says, the exercise is done.